typedserver/ts/servertools/tools.serviceworker.ts

61 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-05-11 10:51:20 +00:00
import * as plugins from '../plugins.js';
import * as paths from '../paths.js';
import * as interfaces from '../../dist_ts_interfaces/index.js'
import { Handler } from './classes.handler.js';
import type { TypedServer } from '../typedserver.classes.typedserver.js';
import { HandlerTypedRouter } from './classes.handlertypedrouter.js';
const lswJS: string = plugins.smartfile.fs.toStringSync(
plugins.path.join(paths.distBundleDir, './lsw.js')
);
const lswJSMeta: string = plugins.smartfile.fs.toStringSync(
plugins.path.join(paths.distBundleDir, './lsw.js.map')
);
let lswVersionInfo: interfaces.serviceworker.IRequest_Serviceworker_Backend_VersionInfo['response'] =
null;
const serviceworkerHandler = new Handler(
'GET',
async (req, res) => {
if (req.path === '/lsw.js') {
res.status(200);
res.set('Content-Type', 'text/javascript');
res.write(lswJS + '\n' + `/** appSemVer: ${lswVersionInfo?.appSemVer || 'not set'} */`);
} else if (req.path === '/lsw.js.map') {
res.status(200);
res.set('Content-Type', 'application/json');
res.write(lswJSMeta);
}
res.end();
}
);
export const addServiceWorkerRoute = (
typedserverInstance: TypedServer,
lswData: () => interfaces.serviceworker.IRequest_Serviceworker_Backend_VersionInfo['response']
) => {
// lets the version info as unique string;
lswVersionInfo = lswData();
// the basic stuff
typedserverInstance.server.addRoute('/lsw.js*', serviceworkerHandler);
// the typed stuff
const typedrouter = new plugins.typedrequest.TypedRouter();
typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.serviceworker.IRequest_Serviceworker_Backend_VersionInfo>(
'serviceworker_versionInfo',
async (req) => {
const versionInfoResponse = lswData();
return versionInfoResponse;
}
)
);
typedserverInstance.server.addRoute(
'/lsw-typedrequest',
new HandlerTypedRouter(typedrouter)
);
};