Created
April 27, 2017 08:58
-
-
Save JasonHewison/c4adf44926a32c458e586e0f64b67d16 to your computer and use it in GitHub Desktop.
nodejs stuff
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
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); | |
}; | |
}; |
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
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 }; | |
} | |
}; |
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
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; | |
}; | |
}; |
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
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