You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.4 KiB
JavaScript
58 lines
1.4 KiB
JavaScript
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,
|
|
}
|
|
})
|