typedserver/ts/servertools/tools.serviceworker.ts

61 lines
2.0 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';
2024-05-14 13:28:09 +00:00
import type { TypedServer } from '../classes.typedserver.js';
2024-05-11 10:51:20 +00:00
import { HandlerTypedRouter } from './classes.handlertypedrouter.js';
2024-05-14 13:28:09 +00:00
const swBundleJs: string = plugins.smartfile.fs.toStringSync(
plugins.path.join(paths.serviceworkerBundleDir, './serviceworker.bundle.js')
2024-05-11 10:51:20 +00:00
);
2024-05-14 13:28:09 +00:00
const swBundleJsMap: string = plugins.smartfile.fs.toStringSync(
plugins.path.join(paths.serviceworkerBundleDir, './serviceworker.bundle.js.map')
2024-05-11 10:51:20 +00:00
);
2024-05-14 13:28:09 +00:00
let swVersionInfo: interfaces.serviceworker.IRequest_Serviceworker_Backend_VersionInfo['response'] =
2024-05-11 10:51:20 +00:00
null;
const serviceworkerHandler = new Handler(
'GET',
async (req, res) => {
2024-05-14 13:28:09 +00:00
if (req.path === '/serviceworker.bundle.js') {
2024-05-11 10:51:20 +00:00
res.status(200);
res.set('Content-Type', 'text/javascript');
2024-05-14 13:28:09 +00:00
res.write(swBundleJs + '\n' + `/** appSemVer: ${swVersionInfo?.appSemVer || 'not set'} */`);
} else if (req.path === '/serviceworker.bundle.js.map') {
2024-05-11 10:51:20 +00:00
res.status(200);
res.set('Content-Type', 'application/json');
2024-05-14 13:28:09 +00:00
res.write(swBundleJsMap);
2024-05-11 10:51:20 +00:00
}
res.end();
}
);
export const addServiceWorkerRoute = (
typedserverInstance: TypedServer,
2024-05-14 13:28:09 +00:00
swDataFunc: () => interfaces.serviceworker.IRequest_Serviceworker_Backend_VersionInfo['response']
2024-05-11 10:51:20 +00:00
) => {
// lets the version info as unique string;
2024-05-14 13:28:09 +00:00
swVersionInfo = swDataFunc();
2024-05-11 10:51:20 +00:00
// the basic stuff
2024-05-25 01:06:17 +00:00
typedserverInstance.server.addRoute('/serviceworker.*', serviceworkerHandler);
2024-05-11 10:51:20 +00:00
// 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) => {
2024-05-14 13:28:09 +00:00
const versionInfoResponse = swDataFunc();
2024-05-11 10:51:20 +00:00
return versionInfoResponse;
}
)
);
typedserverInstance.server.addRoute(
2024-05-14 13:28:09 +00:00
'/sw-typedrequest',
2024-05-11 10:51:20 +00:00
new HandlerTypedRouter(typedrouter)
);
};