fix: Complete TODOS and use promise then, catch, finally

Signed-off-by: Richie Bendall <richiebendall@gmail.com>
This commit is contained in:
Richie Bendall 2019-06-21 16:48:02 +12:00
parent 4f2825fcc7
commit 070c471a7e
No known key found for this signature in database
GPG key ID: 1C6A99DFA9D306FC
2 changed files with 59 additions and 70 deletions

View file

@ -14,21 +14,13 @@ module.exports = async (req, res, next) => {
res.locals.user = { res.locals.user = {
copyright: '<copyright holders>', copyright: '<copyright holders>',
}; };
try { readFile(
const file = await readFile(
path.join(__dirname, '..', 'users', `${id}.json`), path.join(__dirname, '..', 'users', `${id}.json`),
'utf8' 'utf8'
); )
res.locals.user = JSON.parse(file); .then(data => res.locals.user = JSON.parse(data))
} catch (e) { .catch(({code, message}) => {
if (e.code !== 'ENOENT') { if (code !== 'ENOENT') res.code(500).send(`An internal error occurred - open an issue on https://github.com/remy/mit-license with the following information: ${message}`)
// Error is *not* "File not found" })
console.log(e); .finally(() => next())
res.status(500).end();
return;
}
}
next();
}; };

View file

@ -1,6 +1,8 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const { promisify } = require('util'); const {
promisify
} = require('util');
const access = promisify(fs.access); const access = promisify(fs.access);
const writeFile = promisify(fs.writeFile); const writeFile = promisify(fs.writeFile);
const btoa = require('btoa'); const btoa = require('btoa');
@ -11,7 +13,10 @@ var github = require('@octokit/rest')({
userAgent: 'mit-license v' + require(path.join(__dirname, "..", "package.json")).version, userAgent: 'mit-license v' + require(path.join(__dirname, "..", "package.json")).version,
}); });
function getUserData({ query, body }) { function getUserData({
query,
body
}) {
// If query parameters provided // If query parameters provided
if (Object.keys(query).length > 0) return query; if (Object.keys(query).length > 0) return query;
// If the data parsed as {'{data: "value"}': ''} // If the data parsed as {'{data: "value"}': ''}
@ -25,7 +30,9 @@ const validDomain = s => /^[\w-_]+$/.test(s);
// HTTP POST API // HTTP POST API
module.exports = async (req, res) => { module.exports = async (req, res) => {
const { hostname } = req; const {
hostname
} = req;
// Get different parts of hostname (example: remy.mit-license.org -> ['remy', 'mit-license', 'org']) // Get different parts of hostname (example: remy.mit-license.org -> ['remy', 'mit-license', 'org'])
const params = hostname.split('.'); const params = hostname.split('.');
@ -42,7 +49,7 @@ module.exports = async (req, res) => {
const id = params[0]; const id = params[0];
if (!validDomain(id)) { if (!validDomain(id)) {
// return a vague error intentionally // Return a vague error intentionally
res res
.status(400) .status(400)
.send( .send(
@ -53,18 +60,18 @@ module.exports = async (req, res) => {
} }
// Check if the user file exists in the users directory // Check if the user file exists in the users directory
try { access(path.join(__dirname, '..', 'users', `${id}.json`))
const res = await access(path.join(__dirname, '..', 'users', `${id}.json`)); // will throw if doesn't exist .then(() => {
res res
.status(409) .status(409)
.send( .send(
'User already exists - to update values, please send a pull request on https://github.com/remy/mit-license' 'User already exists - to update values, please send a pull request on https://github.com/remy/mit-license'
); )
})
.catch(({code, message}) => {
if (code !== 'ENOENT') {
res.code(500).send(`An internal error occurred - open an issue on https://github.com/remy/mit-license with the following information: ${message}`)
return; return;
} catch (e) {
console.log(e);
// FIXME only allow file doesn't exist to continue
} }
// File doesn't exist // File doesn't exist
@ -74,10 +81,9 @@ module.exports = async (req, res) => {
return; return;
} }
try {
const fileContent = JSON.stringify(userData, 0, 2) const fileContent = JSON.stringify(userData, 0, 2)
const success = await github.repos.createFile({ github.repos.createFile({
owner: 'remy', owner: 'remy',
repo: 'mit-license', repo: 'mit-license',
path: `users/${id}.json`, path: `users/${id}.json`,
@ -87,22 +93,13 @@ module.exports = async (req, res) => {
name: 'MIT License Bot', name: 'MIT License Bot',
email: 'remy@leftlogic.com', email: 'remy@leftlogic.com',
}, },
}); })
.then(() => writeFile(
// TODO copy the user.json into the users/ directory, it'll work
writeFile(
path.join(__dirname, "..", "users", `${id}.json`), path.join(__dirname, "..", "users", `${id}.json`),
fileContent fileContent
); )
.then(() => res.status(201).send(`MIT license page created: https://${hostname}`))
console.log(success); .catch(() => res.status(500).send('Unable to create new user - please send a pull request on https://github.com/remy/mit-license'))
res.status(201).send(`MIT license page created: https://${hostname}`); )
} catch (err) { })
console.log(err);
res
.status(502)
.send(
'Unable to create new user - please send a pull request on https://github.com/remy/mit-license'
);
}
}; };