0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-02-03 23:00:14 -05:00
ghost/core/server/lib/fs/package-json/parse.js
Hannah Wolfe baa8118893 Refactor common pattern in service files
- Use array destructuring
- Use @tryghost/errors
- Part of the big move towards decoupling, this gives visibility on what's being used where
- Biting off manageable chunks / fixing bits of code I'm refactoring for other reasons
2020-04-30 20:48:42 +01:00

56 lines
1.6 KiB
JavaScript

/**
* Dependencies
*/
const Promise = require('bluebird');
const fs = require('fs-extra');
const {i18n} = require('../../common');
/**
* Parse package.json and validate it has
* all the required fields
*/
function parsePackageJson(path) {
return fs.readFile(path)
.catch(function () {
const err = new Error(i18n.t('errors.utils.parsepackagejson.couldNotReadPackage'));
err.context = path;
return Promise.reject(err);
})
.then(function (source) {
let hasRequiredKeys;
let json;
let err;
try {
json = JSON.parse(source);
hasRequiredKeys = json.name && json.version;
if (!hasRequiredKeys) {
err = new Error(i18n.t('errors.utils.parsepackagejson.nameOrVersionMissing'));
err.context = path;
err.help = i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'https://ghost.org/docs/api/handlebars-themes/'});
return Promise.reject(err);
}
return json;
} catch (parseError) {
err = new Error(i18n.t('errors.utils.parsepackagejson.themeFileIsMalformed'));
err.context = path;
err.help = i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'https://ghost.org/docs/api/handlebars-themes/'});
return Promise.reject(err);
}
});
}
/**
* Expose `parsePackageJson`
*/
module.exports = parsePackageJson;