es-dev-server
Version:
Development server for modern web apps
43 lines • 1.74 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPluginServeMiddlware = void 0;
const tslib_1 = require("tslib");
const path_1 = tslib_1.__importDefault(require("path"));
/**
* Sets up a middleware which allows plugins to serve files instead of looking it up in the file system.
*/
function createPluginServeMiddlware(cfg) {
const servePlugins = cfg.plugins.filter(p => 'serve' in p);
if (servePlugins.length === 0) {
// nothing to serve
return (ctx, next) => next();
}
return async function pluginServeMiddleware(context, next) {
var _a;
for (const plugin of servePlugins) {
const response = await ((_a = plugin.serve) === null || _a === void 0 ? void 0 : _a.call(plugin, context));
if (response) {
if (response.body == null) {
throw new Error('A serve result must contain a body. Use the transform hook to change only the mime type.');
}
context.body = response.body;
if (response.type != null) {
context.type = response.type;
}
else {
context.type = path_1.default.extname(path_1.default.basename(context.path));
}
if (response.headers) {
for (const [k, v] of Object.entries(response.headers)) {
context.response.set(k, v);
}
}
context.status = 200;
return;
}
}
return next();
};
}
exports.createPluginServeMiddlware = createPluginServeMiddlware;
//# sourceMappingURL=plugin-serve.js.map