From e6813851bf03a0aa77fbffb9e5d38f2a1b816ed9 Mon Sep 17 00:00:00 2001 From: matt Date: Sun, 23 Jan 2022 22:35:31 +0000 Subject: [PATCH] Added new module for importing JSON files safely, along with test files --- lib/__tests__/importJSON.test.js | 42 ++++++++++++++++++++++++++++++++ lib/importJSON.js | 33 +++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 lib/__tests__/importJSON.test.js create mode 100644 lib/importJSON.js diff --git a/lib/__tests__/importJSON.test.js b/lib/__tests__/importJSON.test.js new file mode 100644 index 0000000..76a8287 --- /dev/null +++ b/lib/__tests__/importJSON.test.js @@ -0,0 +1,42 @@ +'use strict'; + +const importJSON = require('../importJSON'); +const matchers = require('jest-extended'); +const fs = require('fs'); + +expect.extend(matchers); + +describe('importJSON', () => { + test('Import a file from config dir if no dir param given', () => { + const loadedFile = importJSON('db.sample'); + + expect(loadedFile).toBeObject(); + expect(loadedFile.host).toBe('hostname'); + expect(loadedFile.port).toBeNumber(); + expect(loadedFile.port).toBe(1111); + }); + + test('Import a file from specified dir', () => { + const loadedFile = importJSON('db.sample', 'config'); + + expect(loadedFile).toBeObject(); + expect(loadedFile.host).toBe('hostname'); + expect(loadedFile.port).toBeNumber(); + expect(loadedFile.port).toBe(1111); + }); + + test('Fail if file doesn\'t exist', () => { + expect(() => importJSON('bob')) + .toThrowError('Missing file'); + }); + + test('Fail if file is malformed', () => { + fs.mkdirSync('config/test'); + fs.writeFileSync('config/test/test.json', 'bob'); + + expect(() => importJSON('test', 'config/test')) + .toThrowError('Malformed file'); + + fs.rmSync('config/test', { recursive: true }); + }); +}); diff --git a/lib/importJSON.js b/lib/importJSON.js new file mode 100644 index 0000000..8cab152 --- /dev/null +++ b/lib/importJSON.js @@ -0,0 +1,33 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +/** + * importJSON() Function to safely fetch and parse a JSON file + * + * @param {string} filename - The filename of the json file to be loaded + * @param {string} [dir='config'] - The directory to find the JSON file in + * + * @return {Object} The loaded object from the file + */ +function importJSON(filename, dir='config') { + const fullFilename = `${filename}.json`; + const pathToFile = path.join(__dirname, '..', dir, fullFilename); + + // Validate that a file exists with that name within the config dir + if (!fs.existsSync(pathToFile)) + throw new Error(`Missing file (${pathToFile})`); + + // Import the file + let file; + try { + file = require(pathToFile); + } catch { + throw new Error(`Malformed file (${pathToFile})`); + } + + return file; +} + +module.exports = importJSON;