-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
Expand file tree
/
Copy pathapp.ts
More file actions
151 lines (129 loc) · 3.76 KB
/
app.ts
File metadata and controls
151 lines (129 loc) · 3.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import { dirname, isAbsolute, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { App } from '@tinyhttp/app'
import { cors } from '@tinyhttp/cors'
import { Eta } from 'eta'
import { Low } from 'lowdb'
import { json } from 'milliparsec'
import sirv from 'sirv'
import { Data, isItem, Service } from './service.js'
const __dirname = dirname(fileURLToPath(import.meta.url))
const isProduction = process.env['NODE_ENV'] === 'production'
export type AppOptions = {
logger?: boolean
static?: string[]
middleware?: (req: unknown, res: unknown, next: unknown) => void
}
const eta = new Eta({
views: join(__dirname, '../views'),
cache: isProduction,
})
export function createApp(db: Low<Data>, options: AppOptions = {}) {
// Create service
const service = new Service(db)
// Create app
const app = new App()
// Static files
app.use(sirv('public', { dev: !isProduction }))
options.static
?.map((path) => (isAbsolute(path) ? path : join(process.cwd(), path)))
.forEach((dir) => app.use(sirv(dir, { dev: !isProduction })))
// Use middleware if specified
if (options.middleware) {
app.use(options.middleware)
}
// CORS
app
.use((req, res, next) => {
return cors({
allowedHeaders: req.headers['access-control-request-headers']
?.split(',')
.map((h) => h.trim()),
})(req, res, next)
})
.options('*', cors())
// Body parser
// @ts-expect-error expected
app.use(json())
app.get('/', (_req, res) =>
res.send(eta.render('index.html', { data: db.data })),
)
app.get('/:name', (req, res, next) => {
const { name = '' } = req.params
const query = Object.fromEntries(
Object.entries(req.query)
.map(([key, value]) => {
if (
['_start', '_end', '_limit', '_page', '_per_page'].includes(key) &&
typeof value === 'string'
) {
return [key, parseInt(value)]
} else {
return [key, value]
}
})
.filter(([, value]) => !Number.isNaN(value)),
)
res.locals['data'] = service.find(name, query)
next?.()
})
app.get('/:name/:id', (req, res, next) => {
const { name = '', id = '' } = req.params
res.locals['data'] = service.findById(name, id, req.query)
next?.()
})
app.post('/:name', async (req, res, next) => {
const { name = '' } = req.params
if (isItem(req.body)) {
res.locals['data'] = await service.create(name, req.body)
}
next?.()
})
app.put('/:name', async (req, res, next) => {
const { name = '' } = req.params
if (isItem(req.body)) {
res.locals['data'] = await service.update(name, req.body)
}
next?.()
})
app.put('/:name/:id', async (req, res, next) => {
const { name = '', id = '' } = req.params
if (isItem(req.body)) {
res.locals['data'] = await service.updateById(name, id, req.body)
}
next?.()
})
app.patch('/:name', async (req, res, next) => {
const { name = '' } = req.params
if (isItem(req.body)) {
res.locals['data'] = await service.patch(name, req.body)
}
next?.()
})
app.patch('/:name/:id', async (req, res, next) => {
const { name = '', id = '' } = req.params
if (isItem(req.body)) {
res.locals['data'] = await service.patchById(name, id, req.body)
}
next?.()
})
app.delete('/:name/:id', async (req, res, next) => {
const { name = '', id = '' } = req.params
res.locals['data'] = await service.destroyById(
name,
id,
req.query['_dependent'],
)
next?.()
})
app.use('/:name', (req, res) => {
const { data } = res.locals
if (data === undefined) {
res.sendStatus(404)
} else {
if (req.method === 'POST') res.status(201)
res.json(data)
}
})
return app
}