File
Blob: samples/module_fallback/fallback.js
| 1 | #!/usr/bin/env node |
| 2 | |
| 3 | const { createServer } = require('http'); |
| 4 | |
| 5 | const server = createServer((req, res) => { |
| 6 | // The response from the fallback service must be a valid JSON |
| 7 | // serialization of a Worker::Module config. |
| 8 | |
| 9 | // The x-resolve-method tells us if the module was imported or required. |
| 10 | console.log(req.headers['x-resolve-method']); |
| 11 | |
| 12 | // The req.url query params tell us what we are importing |
| 13 | const url = new URL(req.url, "http://example.org"); |
| 14 | const specifier = url.searchParams.get('specifier'); |
| 15 | const referrer = url.searchParams.get('referrer'); |
| 16 | console.log(specifier, referrer); |
| 17 | |
| 18 | // The fallback service can tell the client to map the request |
| 19 | // specifier to another specifier using a 301 redirect, using |
| 20 | // the location header to specify the alternative specifier. |
| 21 | if (specifier == "/foo") { |
| 22 | console.log('Redirecting /foo to /baz'); |
| 23 | res.writeHead(301, { location: '/baz' }); |
| 24 | res.end(); |
| 25 | return; |
| 26 | } |
| 27 | |
| 28 | if (specifier == "/bar") { |
| 29 | res.writeHead(404); |
| 30 | res.end(); |
| 31 | return; |
| 32 | } |
| 33 | |
| 34 | console.log(`Returning module spec for ${specifier}`); |
| 35 | // Returning the name is optional. If it is included, then it MUST match the |
| 36 | // request specifier! |
| 37 | res.end(`{ |
| 38 | "name": "${specifier}", |
| 39 | "esModule":"export default 1;" |
| 40 | }`); |
| 41 | }); |
| 42 | |
| 43 | server.listen(8888, () => { |
| 44 | console.log('ready...'); |
| 45 | }); |