diff --git a/middleware/load-user.js b/middleware/load-user.js index f6f3e8ea..a56f6e28 100644 --- a/middleware/load-user.js +++ b/middleware/load-user.js @@ -14,21 +14,13 @@ module.exports = async (req, res, next) => { res.locals.user = { copyright: '', }; - try { - const file = await readFile( - path.join(__dirname, '..', 'users', `${id}.json`), - 'utf8' - ); - res.locals.user = JSON.parse(file); - } catch (e) { - if (e.code !== 'ENOENT') { - // Error is *not* "File not found" - console.log(e); - - res.status(500).end(); - return; - } - } - - next(); + readFile( + path.join(__dirname, '..', 'users', `${id}.json`), + 'utf8' + ) + .then(data => res.locals.user = JSON.parse(data)) + .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}`) + }) + .finally(() => next()) }; diff --git a/routes/post.js b/routes/post.js index a7e92585..4624e321 100644 --- a/routes/post.js +++ b/routes/post.js @@ -1,6 +1,8 @@ const fs = require('fs'); const path = require('path'); -const { promisify } = require('util'); +const { + promisify +} = require('util'); const access = promisify(fs.access); const writeFile = promisify(fs.writeFile); const btoa = require('btoa'); @@ -11,7 +13,10 @@ var github = require('@octokit/rest')({ userAgent: 'mit-license v' + require(path.join(__dirname, "..", "package.json")).version, }); -function getUserData({ query, body }) { +function getUserData({ + query, + body +}) { // If query parameters provided if (Object.keys(query).length > 0) return query; // If the data parsed as {'{data: "value"}': ''} @@ -25,7 +30,9 @@ const validDomain = s => /^[\w-_]+$/.test(s); // HTTP POST API 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']) const params = hostname.split('.'); @@ -42,7 +49,7 @@ module.exports = async (req, res) => { const id = params[0]; if (!validDomain(id)) { - // return a vague error intentionally + // Return a vague error intentionally res .status(400) .send( @@ -53,56 +60,46 @@ module.exports = async (req, res) => { } // Check if the user file exists in the users directory - try { - const res = await access(path.join(__dirname, '..', 'users', `${id}.json`)); // will throw if doesn't exist - res - .status(409) - .send( - 'User already exists - to update values, please send a pull request on https://github.com/remy/mit-license' - ); + access(path.join(__dirname, '..', 'users', `${id}.json`)) + .then(() => { + res + .status(409) + .send( + '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 + // If copyright property and key doesn't exist + if (!userData.copyright) { + res.status(400).send('JSON requires "copyright" property and value'); + return; + } - // File doesn't exist - // If copyright property and key doesn't exist - if (!userData.copyright) { - res.status(400).send('JSON requires "copyright" property and value'); - return; - } + const fileContent = JSON.stringify(userData, 0, 2) - try { - const fileContent = JSON.stringify(userData, 0, 2) - - const success = await github.repos.createFile({ - owner: 'remy', - repo: 'mit-license', - path: `users/${id}.json`, - message: `Automated creation of user ${id}.`, - content: btoa(fileContent), - committer: { - name: 'MIT License Bot', - email: 'remy@leftlogic.com', - }, - }); - - // TODO copy the user.json into the users/ directory, it'll work - writeFile( - 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' - ); - } + github.repos.createFile({ + owner: 'remy', + repo: 'mit-license', + path: `users/${id}.json`, + message: `Automated creation of user ${id}.`, + content: btoa(fileContent), + committer: { + name: 'MIT License Bot', + email: 'remy@leftlogic.com', + }, + }) + .then(() => writeFile( + path.join(__dirname, "..", "users", `${id}.json`), + fileContent + ) + .then(() => res.status(201).send(`MIT license page created: https://${hostname}`)) + .catch(() => res.status(500).send('Unable to create new user - please send a pull request on https://github.com/remy/mit-license')) + ) + }) };