Skip to content

Commit

Permalink
Merge pull request #55 from solaoi/fix_parallel-stub-requests-error
Browse files Browse the repository at this point in the history
change db client to better-sqlite3 on api mode for fixing error with parallel requests
  • Loading branch information
solaoi authored Jul 5, 2022
2 parents a06aea5 + 4aba735 commit cd45402
Show file tree
Hide file tree
Showing 4 changed files with 2,166 additions and 1,583 deletions.
23 changes: 8 additions & 15 deletions app/api/[[...slug]].ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import { BlitzApiRequest, BlitzApiResponse, BlitzApiHandler } from "blitz"
import db, { prisma } from "db"
import { getProjectIdBy, getStubsBy, updateStubBy } from "../lib/sqlite3Client"

const snooze = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

const dynamicHandler = async (method, slug) => {
const project = await db.project.findFirst({ where: { basePath: `/${slug[0]}` } })
if (!project) {
const dynamicHandler = (method, slug) => {
const projectId = getProjectIdBy(`/${slug[0]}`)
if (projectId === null) {
return null
}
const path = slug.filter((_, i) => i !== 0).join("/")
const stubs = await db.stub.findMany({ where: { projectId: project.id, path: `/${path}` } })

const stubs = getStubsBy(projectId, `/${path}`)
return stubs.filter((stub) => stub.method === method)[0]
}

Expand All @@ -23,7 +22,7 @@ const Handler: BlitzApiHandler = async (req: BlitzApiRequest, res: BlitzApiRespo
res.status(404).end()
return
}
const obj = await dynamicHandler(method, slug)
const obj = dynamicHandler(method, slug)
if (!obj) {
res.status(404).end()
return
Expand Down Expand Up @@ -79,14 +78,8 @@ const Handler: BlitzApiHandler = async (req: BlitzApiRequest, res: BlitzApiRespo
return snooze(sleep * 1000)
}
}

await Promise.all([
sleepFunc(),
db.stub.update({
where: { id },
data: { logs: updatedLogs, ntimesErrorCounter: ntimesErrorCount },
}),
])
const { updateStubWith } = updateStubBy(id)
await Promise.all([sleepFunc(), updateStubWith(updatedLogs, ntimesErrorCount)])

if (inNtimesErrorTerm) {
res.status(Number(ntimesErrorStatusCode)).end()
Expand Down
59 changes: 59 additions & 0 deletions app/lib/sqlite3Client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import Database from "better-sqlite3"
import { join } from "path"

const database = process.env.DATABASE_URL
if (database === undefined) throw new Error()
const databasePath =
process.env.NODE_ENV !== "production"
? join(process.cwd(), "db", database.replace("file:", ""))
: database.replace("file:", "")

const db = new Database(databasePath, { fileMustExist: true })

const getProjectIdByPreparedStatement = db.prepare("SELECT id FROM Project WHERE basePath = ?")
const getProjectIdBy = (basePath: string): number | null => {
const row = getProjectIdByPreparedStatement.get(basePath)
return row !== undefined ? row.id : null
}

type StubTableType = {
id: number
createdAt: string
updatedAt: string
createdBy: string
updatedBy: string
path: string
method: string
contentType: string
statusCode: string
response: string
sleep: number
logs: string
ntimesError: number
ntimesErrorStatusCode: string
ntimesErrorCounter: number
memo: string
projectId: number
}

const getStubsByPreparedStatement = db.prepare(
"SELECT * FROM Stub WHERE projectId = ? AND path = ?"
)
const getStubsBy = (projectId: number, path: string): StubTableType[] => {
return getStubsByPreparedStatement.all(projectId, path)
}

const updateStubWithPreparedStatement = db.prepare(
"UPDATE Stub SET logs = ?, ntimesErrorCounter = ? WHERE id = ?"
)
const updateStubBy = (id: number) => {
const updateStubWith = (logs: string, ntimesErrorCounter: number) => {
return new Promise((resolve) => {
const info = updateStubWithPreparedStatement.run(logs, ntimesErrorCounter, id)
resolve(info.changes)
})
}
return { updateStubWith }
}

export { getProjectIdBy, getStubsBy, updateStubBy }
Loading

0 comments on commit cd45402

Please sign in to comment.