@intuitionrobotics/thunderstorm
Version:
89 lines • 3.27 kB
JavaScript
import { BeLogged, LogClient, LogClient_Function, LogClient_Terminal, Module } from "@intuitionrobotics/ts-common";
import { Firebase_ExpressFunction, FirebaseFunction } from '@intuitionrobotics/firebase/backend-functions';
import { HttpServer_Class } from "../modules/server/HttpServer.js";
import { ServerApi } from "../modules/server/server-api.js";
import { BaseStorm } from "./BaseStorm.js";
import express from "express";
import {} from "express";
import { DefaultApiErrorMessageComposer } from "../modules/server/server-errors.js";
import { FirebaseModule } from "@intuitionrobotics/firebase/backend";
export class Storm extends BaseStorm {
// v2.0: consumers build an Express Router by hand and hand it here.
// The framework `app.use`s it during build(); there is no other path.
routes;
initialPath;
functions = [];
express;
logClient = LogClient_Function;
onDestroy;
onStart;
errorMessageComposer = DefaultApiErrorMessageComposer();
constructor() {
super();
this.addModules(FirebaseModule);
}
setErrorMessageComposer(errorMessageComposer) {
this.errorMessageComposer = errorMessageComposer;
return this;
}
setApp(app) {
this.express = app;
return this;
}
setLogClient(logClient) {
this.logClient = logClient;
return this;
}
getLogClient() {
return this.logClient;
}
setOnDestroy(onDestroy) {
this.onDestroy = onDestroy;
return this;
}
setOnStart(onStart) {
this.onStart = onStart;
return this;
}
static getInstance() {
return Storm.instance;
}
init() {
BeLogged.addClient(process.env.GCLOUD_PROJECT && process.env.FUNCTIONS_EMULATOR ? LogClient_Terminal : this.logClient);
ServerApi.isDebug = !!this.config?.isDebug;
super.init();
return this;
}
// The caller passes a fully-built Express Router; Storm wires it onto the
// HttpServer's express app at build() time.
setRoutes(routes) {
this.routes = routes;
return this;
}
setInitialRoutePath(initialPath) {
this.initialPath = initialPath;
return this;
}
build(onStarted) {
const app = this.express || express();
const httpServer = new HttpServer_Class(app, this.config?.["HttpServer"]);
const modulesAsFunction = this.modules.filter((module) => module instanceof FirebaseFunction);
this.functions = [new Firebase_ExpressFunction(app), ...modulesAsFunction];
if (this.onStart)
this.functions.forEach(func => func.addOnStart(this.onStart));
if (this.onDestroy)
this.functions.forEach(func => func.addOnDestroy(this.onDestroy));
this.init();
httpServer.init();
const urlPrefix = !process.env.GCLOUD_PROJECT ? this.initialPath : "";
if (this.routes)
httpServer.mountRouter(this.routes, urlPrefix);
if (onStarted)
onStarted().catch(e => this.logError(e));
return this.functions.reduce((toRet, _function) => {
toRet[_function.getName()] = _function.getFunction();
return toRet;
}, {});
}
}
//# sourceMappingURL=Storm.js.map