UNPKG

1.94 kBJavaScriptView Raw
1import env, { isDev, stage } from '@lskjs/env';
2import flattenKeys from '@lskjs/utils/flattenKeys';
3import mapValuesDeep from '@lskjs/utils/mapValuesDeep';
4import serializeWindow from '@lskjs/utils/serializeWindow';
5import isPlainObject from 'lodash/isPlainObject';
6import pickBy from 'lodash/pickBy';
7
8import Api from './Api';
9import awaitHealthchecks from './utils/awaitHealthcheck';
10
11export class IndexApi extends Api {
12 async healthcheck(req) {
13 if (!this.app) return awaitHealthchecks({ healthcheck: null });
14 if (this.app.healthcheck) return awaitHealthchecks({ healthcheck: await this.app.healthcheck(req) });
15 if (this.app.healthchecks) return awaitHealthchecks(this.app.healthchecks(req));
16 return awaitHealthchecks({ healthcheck: null });
17 }
18 __getRoutesList(tree = false) {
19 if (tree) {
20 return mapValuesDeep(
21 this.getRoutes(),
22 (a) => a,
23 (res2) => (isPlainObject(res2) ? pickBy(res2, Boolean) : res2),
24 );
25 }
26 return flattenKeys(this.getRoutes(), [], (a) => a.join(''));
27 }
28 index() {
29 const url = this.path;
30 const res = {
31 message: `Current API version is here: ${url}`,
32 url,
33 };
34 if (isDev) {
35 res.routes = this.__getRoutesList(true);
36 }
37 return res;
38 }
39 env(req) {
40 return {
41 __ROOT_STATE__: {
42 token: req.token,
43 user: req.user,
44 req: {
45 token: req.token,
46 user: req.user,
47 },
48 config: this.app.config.client || {},
49 },
50 ...env,
51 __DEV__: isDev,
52 __STAGE__: stage,
53 };
54 }
55 envjs(req, res) {
56 return res.send(serializeWindow(this.env(req)));
57 }
58 getRoutes() {
59 return {
60 ...super.getRoutes(),
61 '/': this.index.bind(this),
62 '/env': this.env.bind(this),
63 '/env.json': this.env.bind(this),
64 '/env.js': this.envjs.bind(this),
65 '/healthcheck': this.healthcheck.bind(this),
66 };
67 }
68}
69
70export default IndexApi;