pull/1/head
Antonio De Lucreziis 2 years ago
parent 8719ba3279
commit ea722e51cd

@ -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,
}
})

@ -4,18 +4,43 @@ import express from 'express'
import bodyParser from 'body-parser' import bodyParser from 'body-parser'
import { loggingMiddleware, PingRouter, StatusRouter } from './server/helpers.js' import { loggingMiddleware, PingRouter, StatusRouter } from './server/helpers.js'
import { createDatabase, getUser, updateUser } from './db/database.js'
const app = express() const app = express()
const db = createDatabase('./db.local.json', {
users: {
BachoSeven: {
email: 'foo@bar.com',
password: '123',
},
},
problems: {},
})
app.use(bodyParser.json()) app.use(bodyParser.json())
app.use(loggingMiddleware) app.use(loggingMiddleware)
app.use('/api/status', new StatusRouter()) app.use('/api/status', new StatusRouter())
app.use('/api/ping', new PingRouter()) app.use('/api/ping', new PingRouter())
app.all('*', (req, res) => { app.get('/api/user/:id', async (req, res) => {
res.status(404) const user = await getUser(db, req.params.id)
res.end('Not found')
if (user) {
res.json(user)
} else {
res.sendStatus(404)
}
})
app.post('/api/user/:id', async (req, res) => {
await updateUser(db, req.params.id, req.body)
res.sendStatus(200)
})
app.all('*', (_req, res) => {
res.sendStatus(404)
}) })
app.listen(4000, () => { app.listen(4000, () => {

Loading…
Cancel
Save