Created
January 16, 2020 19:00
-
-
Save tudorilisoi/69afb952aa6fbbd099432c20b1486030 to your computer and use it in GitHub Desktop.
This file contains hidden or 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").config(); | |
const express = require("express"); | |
const morgan = require("morgan"); | |
const cors = require("cors"); | |
const helmet = require("helmet"); | |
const { NODE_ENV } = require("./config"); | |
const app = express(); | |
const morganOption = NODE_ENV === "production" ? " tiny" : "common"; | |
const pc = async (fn) => { | |
try { | |
const retVal = await fn() | |
return [null, retVal] | |
} catch (error) { | |
return [error, null] | |
} | |
} | |
const asyncHelper = (value, error = null) => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (error) { | |
reject(error) | |
} else { | |
resolve(value) | |
} | |
}, Math.random() * 1000 * 3) | |
}) | |
} | |
const dataService = { | |
getRand: async () => { | |
return asyncHelper(null, new Error('NO_ENTROPY')) | |
// return asyncHelper(42) | |
} | |
} | |
app.use(morgan(morganOption)); | |
app.use(helmet()); | |
app.use(cors()); | |
app.get("/", (req, res) => { | |
x.nothing() //this breaks | |
res.send("<h1>Hello, world!</h1>"); | |
}); | |
app.get("/api/rand", async (req, res, next) => { | |
// const [error, value] = await pc(()=>43) | |
const [error, value] = await pc(dataService.getRand) | |
if (error) { | |
// return next(error) | |
return req.redirect('/login') | |
} | |
res.json({ value }) | |
/* | |
//standard try-catch without pc the helper | |
try { | |
const value = await dataService.getRand() | |
res.json({ value }) | |
} catch (err) { | |
return next(err) | |
} */ | |
}); | |
app.use(function erroHandler(error, req, res, next) { | |
const isAPI = /^\/api\//g.test(req.path) | |
if (!isAPI) { | |
return res.status(500).send(` | |
<pre> | |
${error} | |
${error.stack} | |
</pre> | |
`) | |
} | |
let response; | |
if (NODE_ENV === "production") { | |
response = { error: { message: "server error" } }; | |
} else { | |
console.error(error); | |
response = { message: error.message, error }; | |
} | |
res.status(500).json(response); | |
}); | |
module.exports = app; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment