Skip to content

Instantly share code, notes, and snippets.

@JasonHewison
Created April 27, 2017 08:58
Show Gist options
  • Save JasonHewison/c4adf44926a32c458e586e0f64b67d16 to your computer and use it in GitHub Desktop.
Save JasonHewison/c4adf44926a32c458e586e0f64b67d16 to your computer and use it in GitHub Desktop.
nodejs stuff
module.exports = function asyncRequest(action) {
return async (req, res) => {
const { status = 200, headers, body } = await action(req);
if (body && typeof body !== "string" && typeof body !== "number") {
res.writeHead(status, headers || { "Content-Type": "application/json" });
return res.end(JSON.stringify(body));
}
if (typeof body === "undefined") {
res.writeHead(status, headers || {});
return res.end();
}
res.writeHead(status, headers || { "Content-Type": "text/plain" });
return res.end(body);
};
};
const users = require('users');
const emails = require('emails');
module.exports = {
async login(req) {
const id = req.param('id');
let user;
if(user = users.find(id)){
const token = users.createResetToken();
await emails.send(user, token);
}
return { status: 204 };
}
};
module.exports = async function minTimeToComplete(minTime, action) {
return async (req) => {
const wait = new Promise((resolve) => setTimeout(resolve, minTime));
const [response] = await Promise.all([action(req), wait]);
return response;
};
};
const asyncRequest = require('./asyncRequest');
const minTimeToComplete = require('./minTimeToComplete');
const Controller = require('./Controller');
//...
router.get('/login', asyncRequest(minTimeToComplete(2000, Controller.login)));
//...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment