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' )
); .then(data => res.locals.user = JSON.parse(data))
res.locals.user = JSON.parse(file); .catch(({code, message}) => {
} catch (e) { 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}`)
if (e.code !== 'ENOENT') { })
// Error is *not* "File not found" .finally(() => next())
console.log(e);
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,56 +60,46 @@ 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; // File doesn't exist
} catch (e) { // If copyright property and key doesn't exist
console.log(e); if (!userData.copyright) {
// FIXME only allow file doesn't exist to continue res.status(400).send('JSON requires "copyright" property and value');
} return;
}
// File doesn't exist const fileContent = JSON.stringify(userData, 0, 2)
// If copyright property and key doesn't exist
if (!userData.copyright) {
res.status(400).send('JSON requires "copyright" property and value');
return;
}
try { github.repos.createFile({
const fileContent = JSON.stringify(userData, 0, 2) owner: 'remy',
repo: 'mit-license',
const success = await github.repos.createFile({ path: `users/${id}.json`,
owner: 'remy', message: `Automated creation of user ${id}.`,
repo: 'mit-license', content: btoa(fileContent),
path: `users/${id}.json`, committer: {
message: `Automated creation of user ${id}.`, name: 'MIT License Bot',
content: btoa(fileContent), email: 'remy@leftlogic.com',
committer: { },
name: 'MIT License Bot', })
email: 'remy@leftlogic.com', .then(() => writeFile(
}, path.join(__dirname, "..", "users", `${id}.json`),
}); fileContent
)
// TODO copy the user.json into the users/ directory, it'll work .then(() => res.status(201).send(`MIT license page created: https://${hostname}`))
writeFile( .catch(() => res.status(500).send('Unable to create new user - please send a pull request on https://github.com/remy/mit-license'))
path.join(__dirname, "..", "users", `${id}.json`), )
fileContent })
);
console.log(success);
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'
);
}
}; };