Created
February 19, 2019 13:30
-
-
Save sovietspy2/68fa6337c843d28519ed1397c773ff13 to your computer and use it in GitHub Desktop.
Now v2 local dev for Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require("dotenv-safe").config(); | |
const url = require("url"); | |
const now = require("./now.json"); | |
const routes = now.routes | |
.filter(route => | |
now.builds.some( | |
build => | |
build.src.startsWith(`${route.dest.substring(1)}/`) && | |
["@now/node", "@now/node@canary"].includes(build.use) | |
) | |
) | |
.reduce( | |
(acc, route) => ({ | |
...acc, | |
[route.src]: require(`.${route.dest}`) | |
}), | |
{} | |
); | |
const routeKeys = Object.keys(routes); | |
console.info( | |
`Found ${routeKeys.length} lambdas!\n\n`, | |
JSON.stringify(routeKeys, null, 2) | |
); | |
module.exports = async (req, res) => { | |
const { pathname } = url.parse(req.url); | |
const key = routeKeys.find(key => pathname.match(new RegExp(key))); | |
if (!key) { | |
res.writeHead(404); | |
res.end(); | |
return; | |
} | |
try { | |
await routes[key](req, res); | |
} catch (err) { | |
console.error(err); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"builds": [ | |
{ "src": "services/node-one/index.js", "use": "@now/node@canary" }, | |
{ "src": "services/node-two/index.js", "use": "@now/node" }, | |
{ "src": "services/static-www/package.json", "use": "@now/static-build" } | |
], | |
"routes": [ | |
{ "src": "^/api/one", "dest": "/services/node-one" }, | |
{ "src": "^/api/two", "dest": "/services/node-two" }, | |
{ "src": "^/(.*)", "dest": "/services/static-www/$1" } | |
], | |
"version": 2 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"author": "Pier-Luc Gendreau", | |
"license": "MIT", | |
"main": "index.js", | |
"scripts": { | |
"dev": "micro-dev" | |
}, | |
"devDependencies": { | |
"dotenv-safe": "^6.1.0", | |
"micro": "^9.3.3", | |
"micro-dev": "^3.0.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment