-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.ts
60 lines (51 loc) 路 1.5 KB
/
index.ts
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
import express from 'express'
import { type App, context, methodFromHttp } from 'mangobase'
import cors from 'cors'
/**
* No-op server adapter for express
*/
function expressServer(mangobaseApp: App): express.Express {
const app = express()
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
return withExpress(app, mangobaseApp)
}
/**
* Use this function if you have a custom express instance. Remember to set `cors`, `json` and `urlencoded`.
* These are critical to how to how mangobase works.
*
* @example
* ```
* import cors from 'cors'
*
* const app = express()
* app.use(cors())
* app.use(express.json())
* app.use(express.urlencoded({ extended: true }))
* ```
*/
function withExpress(app: express.Express, mangobaseApp: App): express.Express {
app.all(['/api', '/api/*'], (req, res) => {
// [ ]: handle OPTIONS
const ctx = context({
data: req.body,
headers: req.headers as Record<string, string | string[]>,
method: methodFromHttp(req.method),
path: req.path.replace(/^\/api\/?/, ''),
query: req.query,
url: req.url,
})
mangobaseApp.api(ctx).then((context) => {
res.status(context.statusCode || 200).json(context.result)
})
})
app.get(['/_', '/_/*'], (req, res) => {
const [path, queryParams] = req.url.replace(/^\/_/, '').split('?')
mangobaseApp.admin(path || 'index.html').then((file) => {
res.sendFile(file)
})
})
return app
}
export { expressServer, withExpress }