Refactoring to Typescript...
This commit is contained in:
@@ -2,21 +2,39 @@ import crypto from 'crypto'
|
||||
|
||||
import { readFile, writeFile, access, constants } from 'fs/promises'
|
||||
|
||||
function once(fn, message) {
|
||||
import {
|
||||
CommonProps as MetaProps,
|
||||
Problem,
|
||||
ProblemId,
|
||||
Solution,
|
||||
SolutionId,
|
||||
User,
|
||||
UserId,
|
||||
} from '../../shared/model'
|
||||
|
||||
function once<T extends (...args: any) => any>(fn: T, message: string): T {
|
||||
let flag = false
|
||||
|
||||
return (...args) => {
|
||||
return ((...args: any) => {
|
||||
if (flag) {
|
||||
throw new Error(message ?? `cannot run more than once`)
|
||||
}
|
||||
flag = true
|
||||
return fn(...args)
|
||||
}
|
||||
}) as T
|
||||
}
|
||||
|
||||
function createMutex() {
|
||||
interface Lock {
|
||||
(): void
|
||||
}
|
||||
|
||||
interface Mutex {
|
||||
lock(): Promise<Lock>
|
||||
}
|
||||
|
||||
function createMutex(): Mutex {
|
||||
let locked = false
|
||||
const waiters = []
|
||||
const waiters: ((fn: () => void) => void)[] = []
|
||||
|
||||
const unlock = () => {
|
||||
if (waiters.length > 0) {
|
||||
@@ -29,7 +47,7 @@ function createMutex() {
|
||||
}
|
||||
}
|
||||
|
||||
const lock = () => {
|
||||
const lock = (): Promise<Lock> => {
|
||||
if (locked) {
|
||||
console.log(`[Mutex] Putting into queue`)
|
||||
return new Promise(resolve => {
|
||||
@@ -38,20 +56,26 @@ function createMutex() {
|
||||
} else {
|
||||
console.log(`[Mutex] Acquiring the lock`)
|
||||
locked = true
|
||||
return once(unlock, `lock already released`)
|
||||
return Promise.resolve(once(unlock, `lock already released`))
|
||||
}
|
||||
}
|
||||
|
||||
return { lock }
|
||||
}
|
||||
|
||||
// l = createLock()
|
||||
// unlock1 = await l.lock() // immediate
|
||||
// unlock2 = await l.lock() // hangs...
|
||||
// unlock1() // l2 restarts...
|
||||
// unlock2() // no waiters so noop
|
||||
type DatabaseConnection = {
|
||||
path: string
|
||||
initialValue: Database
|
||||
mu: Mutex
|
||||
}
|
||||
|
||||
export function createDatabase(path, initialValue) {
|
||||
export type Database = {
|
||||
users: Record<string, User>
|
||||
problems: Record<string, Problem>
|
||||
solutions: Record<string, Solution>
|
||||
}
|
||||
|
||||
export function createDatabase(path: string, initialValue: Database) {
|
||||
return {
|
||||
path,
|
||||
initialValue,
|
||||
@@ -59,8 +83,11 @@ export function createDatabase(path, initialValue) {
|
||||
}
|
||||
}
|
||||
|
||||
async function withDatabase({ path, initialValue, mu }, fn) {
|
||||
const unlock = await mu.lock()
|
||||
async function withDatabase<R>(
|
||||
{ path, initialValue, mu }: DatabaseConnection,
|
||||
fn: (db: Database) => R | Promise<R>
|
||||
): Promise<R> {
|
||||
const unlock: Lock = await mu.lock()
|
||||
|
||||
try {
|
||||
await access(path, constants.R_OK)
|
||||
@@ -82,43 +109,30 @@ async function withDatabase({ path, initialValue, mu }, fn) {
|
||||
return result
|
||||
}
|
||||
|
||||
export const getUsers = db =>
|
||||
//
|
||||
// Users
|
||||
//
|
||||
|
||||
export const getUsers = (db: DatabaseConnection) =>
|
||||
withDatabase(db, state => {
|
||||
return Object.values(state.users)
|
||||
})
|
||||
|
||||
export const getUser = (db, id) =>
|
||||
withDatabase(db, state => {
|
||||
export const getUser = (db: DatabaseConnection, id: string) =>
|
||||
withDatabase(db, (state: Database): User | null => {
|
||||
return state.users[id] ?? null
|
||||
})
|
||||
|
||||
// export const createUser = (db, { email, username }) =>
|
||||
// withDatabase(db, state => {
|
||||
// state.users[username] = {
|
||||
// email,
|
||||
// username,
|
||||
// }
|
||||
// })
|
||||
|
||||
// export const updateUser = (db, username, { email, password }) =>
|
||||
// withDatabase(db, state => {
|
||||
// state.users[username] = {
|
||||
// email,
|
||||
// password,
|
||||
// }
|
||||
// })
|
||||
|
||||
//
|
||||
// Problems
|
||||
//
|
||||
|
||||
export const createProblem = (db, { content, createdBy }) =>
|
||||
export const createProblem = (
|
||||
db: DatabaseConnection,
|
||||
{ content, createdBy }: Omit<Problem, 'id' | 'createdAt'>
|
||||
): Promise<ProblemId> =>
|
||||
withDatabase(db, state => {
|
||||
const nextId = (
|
||||
Object.keys(state.problems)
|
||||
.map(k => parseInt(k))
|
||||
.reduce((acc, id) => Math.max(acc, id)) + 1
|
||||
).toString()
|
||||
const nextId = (Object.keys(state.problems).length + 1).toString() as ProblemId
|
||||
|
||||
state.problems[nextId] = {
|
||||
id: nextId,
|
||||
@@ -130,12 +144,12 @@ export const createProblem = (db, { content, createdBy }) =>
|
||||
return nextId
|
||||
})
|
||||
|
||||
export const getProblem = (db, id) =>
|
||||
export const getProblem = (db: DatabaseConnection, id: string): Promise<Problem> =>
|
||||
withDatabase(db, state => {
|
||||
return state.problems[id]
|
||||
})
|
||||
|
||||
export const getProblems = db =>
|
||||
export const getProblems = (db: DatabaseConnection): Promise<Problem[]> =>
|
||||
withDatabase(db, state => {
|
||||
return Object.values(state.problems)
|
||||
})
|
||||
@@ -144,31 +158,52 @@ export const getProblems = db =>
|
||||
// Solutions
|
||||
//
|
||||
|
||||
export const createSolution = (db, { userId, problemId, content }) =>
|
||||
export const createSolution = (
|
||||
db: DatabaseConnection,
|
||||
{ sentBy, forProblem, content }: Omit<Solution, MetaProps>
|
||||
): Promise<SolutionId> =>
|
||||
withDatabase(db, state => {
|
||||
const id = crypto.randomBytes(10).toString('hex')
|
||||
state.solutions[id] = {
|
||||
id,
|
||||
userId,
|
||||
problemId,
|
||||
sentBy,
|
||||
forProblem,
|
||||
content,
|
||||
status: 'pending',
|
||||
}
|
||||
|
||||
return id
|
||||
})
|
||||
|
||||
export const getSolution = (db, id) =>
|
||||
export const getSolution = (db: DatabaseConnection, id: SolutionId): Promise<Solution> =>
|
||||
withDatabase(db, state => {
|
||||
return state.solutions[id]
|
||||
})
|
||||
|
||||
export const getSolutions = (db, { userId, problemId } = {}) =>
|
||||
export const updateSolution = (
|
||||
db: DatabaseConnection,
|
||||
id: SolutionId,
|
||||
solution: Omit<Solution, MetaProps>
|
||||
): Promise<Solution> =>
|
||||
withDatabase(db, state => {
|
||||
state.solutions[id] = { id, ...solution }
|
||||
return state.solutions[id]
|
||||
})
|
||||
|
||||
type SolutionsQuery = Partial<{
|
||||
sentBy: UserId
|
||||
forProblem: ProblemId
|
||||
}>
|
||||
|
||||
export const getSolutions = (db: DatabaseConnection, { sentBy, forProblem }: SolutionsQuery = {}) =>
|
||||
withDatabase(db, state => {
|
||||
let solutions = Object.values(state.solutions)
|
||||
|
||||
if (userId) {
|
||||
solutions = solutions.filter(s => s.userId === userId)
|
||||
if (sentBy) {
|
||||
solutions = solutions.filter(s => s.sentBy === sentBy)
|
||||
}
|
||||
if (problemId) {
|
||||
solutions = solutions.filter(s => s.problemId === problemId)
|
||||
if (forProblem) {
|
||||
solutions = solutions.filter(s => s.forProblem === forProblem)
|
||||
}
|
||||
|
||||
return solutions
|
||||
@@ -1,7 +0,0 @@
|
||||
export const initialDatabaseValue = {
|
||||
users: {
|
||||
['BachoSeven']: {},
|
||||
['aziis98']: {},
|
||||
},
|
||||
problems: {},
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { UserId } from '../../shared/model'
|
||||
import { Database } from './database'
|
||||
|
||||
export const initialDatabaseValue: Database = {
|
||||
users: {
|
||||
['BachoSeven']: {
|
||||
id: 'BachoSeven' as UserId,
|
||||
role: 'admin',
|
||||
},
|
||||
['aziis98']: {
|
||||
id: 'aziis98' as UserId,
|
||||
role: 'admin',
|
||||
},
|
||||
},
|
||||
problems: {},
|
||||
solutions: {},
|
||||
}
|
||||
Reference in New Issue
Block a user