UNPKG

1.41 kBJavaScriptView Raw
1require("./");
2
3var express = module.parent ? module.parent.require("express") : require("express");
4
5patchResponse(express.response);
6delete require.cache[__filename];
7
8module.exports = function markoAppMiddleware() {
9 var sacrificialApp = express();
10
11 sacrificialApp.once("mount", function onmount(parent) {
12 // Patch the response
13 patchResponse(parent.response);
14
15 // Remove sacrificial express app
16 if (parent._router) {
17 // Support Express <= 4.x
18 parent._router.stack.pop();
19 } else {
20 // Support express 5.x
21 parent.router.stack.pop();
22 }
23 });
24
25 return sacrificialApp;
26};
27
28function patchResponse(response) {
29 response.marko = response.marko || function (template, data) {
30 if (typeof template === "string") {
31 throw new Error("res.marko does not take a template name or path like res.render. " + "Instead you should use `require('./path/to/template.marko')` " + "and pass the loaded template to this function.");
32 }
33
34 var res = this;
35 var req = res.req;
36 var app = res.app;
37 var $global = Object.assign({ app, req, res }, app.locals, res.locals);
38
39 if (data) {
40 data = Object.assign(data, {
41 $global: Object.assign($global, data.$global)
42 });
43 } else {
44 data = { $global };
45 }
46
47 res.set({ "content-type": "text/html; charset=utf-8" });
48 return template.render(data, res).on("error", req.next);
49 };
50}
\No newline at end of file