-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpress.js
86 lines (77 loc) · 2.57 KB
/
express.js
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
'use strict';
const Backend = require('./backend');
const express = require('express');
const frontend = require('./frontend');
const { toRoute, objectRouter } = require('extrovert');
module.exports = async function(apiUrl, conn, options) {
const router = express.Router();
const mothershipUrl = options?._mothershipUrl || 'https://mongoose-js.netlify.app/.netlify/functions';
let workspace = null;
if (options?.apiKey) {
({ workspace } = await fetch(`${mothershipUrl}/getWorkspace`, {
method: 'POST',
body: JSON.stringify({ apiKey: options.apiKey }),
headers: {
'Authorization': `Bearer ${options.apiKey}`,
'Content-Type': 'application/json'
}
})
.then(response => {
if (response.status < 200 || response.status >= 400) {
return response.json().then(data => {
throw new Error(`Mongoose Studio API Key Error ${response.status}: ${require('util').inspect(data)}`);
});
}
return response;
})
.then(res => res.json()));
}
apiUrl = apiUrl || 'api';
const backend = Backend(conn);
router.use(
'/api',
function authorize(req, res, next) {
if (!workspace) {
next();
return;
}
const authorization = req.headers.authorization;
const params = {
method: 'POST',
body: JSON.stringify({ workspaceId: workspace._id }),
headers: {
'Authorization': authorization,
'Content-Type': 'application/json'
}
};
fetch(`${mothershipUrl}/me`, params)
.then(response => {
if (response.status < 200 || response.status >= 400) {
return response.json().then(data => {
throw new Error(`Mongoose Studio API Key Error ${response.status}: ${require('util').inspect(data)}`);
});
}
return response;
})
.then(res => res.json())
.then(({ user, roles }) => {
if (!user || !roles) {
throw new Error('Not authorized');
}
req.params.roles = roles;
next();
})
.catch(err => next(err));
},
express.json(),
objectRouter(backend, toRoute)
);
console.log('Workspace', workspace);
const { config } = await frontend(apiUrl, false, options, workspace);
router.get('/config.js', function (req, res) {
res.setHeader('Content-Type', 'application/javascript');
res.end(`window.MONGOOSE_STUDIO_CONFIG = ${JSON.stringify(config, null, 2)};`);
});
router.use(express.static(`${__dirname}/frontend/public`));
return router;
}