Intermediate refactoring...

This commit is contained in:
2022-11-07 00:00:01 +01:00
parent 471fad6d61
commit 5142d4c551
23 changed files with 1648 additions and 1728 deletions
+57
View File
@@ -0,0 +1,57 @@
import { readFile, writeFile, access, constants } from 'fs/promises'
export function createDatabase(path, initialValue) {
return { path, initialValue }
}
async function withDatabase({ path, initialValue }, fn) {
try {
await access(path, constants.R_OK)
} catch (e) {
console.log(`Creating empty database into "${path}"`)
await writeFile(path, JSON.stringify(initialValue, null, 2))
}
console.log(`Loading database from "${path}"`)
const state = JSON.parse(await readFile(path, 'utf-8'))
const result = await fn(state)
console.log(`Saving database to "${path}"`)
await writeFile(path, JSON.stringify(state, null, 2))
return result
}
function createTable(tableName) {
return {
create() {},
get() {},
update() {},
delete() {},
}
}
export const User = createTable('users')
export const Problem = createTable('problems')
export const getUser = (db, id) =>
withDatabase(db, state => {
return state.users[id]
})
export const createUser = (db, { email, username, password }) =>
withDatabase(db, state => {
state.users[email] = {
username,
password,
}
})
export const updateUser = (db, username, { email, password }) =>
withDatabase(db, state => {
state.users[username] = {
email,
password,
}
})