Skip to content

Commit

Permalink
refactor: reduce named export complexity
Browse files Browse the repository at this point in the history
  • Loading branch information
jorgecasar committed Jan 31, 2024
1 parent b17f22b commit a9b12a1
Show file tree
Hide file tree
Showing 37 changed files with 2,421 additions and 1,947 deletions.
2,259 changes: 1,241 additions & 1,018 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
],
"scripts": {
"start": "node .",
"test": "mocha --loader=esmock -- test --reporter spec",
"test": "mocha -- test --reporter spec",
"test:coverage": "c8 --all --include=src --exclude=src/types --exclude=src/index.js --reporter=cobertura --reporter=text npm run test",
"test:coverage:html": "c8 --all --include=src --exclude=src/types --exclude=src/index.js --reporter=html --reporter=text npm run test",
"lint": "npm run lint:check",
Expand Down Expand Up @@ -57,8 +57,9 @@
"@types/sinon": "^10.0.19",
"@types/sinon-chai": "^3.2.10",
"c8": "^8.0.1",
"chai-as-promised": "^7.1.1",
"eslint-config-prettier": "^9.0.0",
"esmock": "^2.6.0",
"esmock": "^2.6.3",
"husky": "^8.0.0",
"mocha": "^10.2.0",
"mock-fs": "^5.2.0",
Expand Down
6 changes: 3 additions & 3 deletions src/errors/mock-runner-error.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { colourHelper, colourCodes } from '../helpers/colours.js';
import { paintText, colourCodes } from '../helpers/colours.js';
import { Logger } from '../helpers/logger.js';

export class MockRunnerError extends Error {
Expand Down Expand Up @@ -38,10 +38,10 @@ export class MockRunnerError extends Error {
type = colourCodes.fg.cyan;
}
Logger.error(
`Error of level ${colourHelper.paintText(this.level.toString(), type)}, type ${colourHelper.paintText(
`Error of level ${paintText(this.level.toString(), type)}, type ${paintText(
this.code.toString(),
colourCodes.fg.gray
)} over ${colourHelper.paintText(this.emitter, colourCodes.fg.blue)}`
)} over ${paintText(this.emitter, colourCodes.fg.blue)}`
);
Logger.info(`${this.stack}`);
}
Expand Down
1 change: 1 addition & 0 deletions src/errors/openapi-schema-not-found-error.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { messages } from '../helpers/messages.js';

export class OpenApiSchemaNotFoundError extends Error {
constructor() {
super(messages.OPENAPI_SCHEMA_NOT_FOUND_ERROR_MSG);
Expand Down
4 changes: 1 addition & 3 deletions src/helpers/colours.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@ export const colourCodes = Object.freeze({
* @param {string} color - The desired color to paint the text.
* @returns {string} - The painted text.
*/
function paintText(text, color) {
export function paintText(text, color) {
return `${color}${text}${colourCodes.reset}`;
}

export const colourHelper = { paintText };
4 changes: 1 addition & 3 deletions src/helpers/verify-remote-origin.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* @param {string} origin - The origin to verify.
* @returns {boolean} True if the origin is remote, false otherwise.
*/
function verifyRemoteOrigin(origin) {
export function verifyRemoteOrigin(origin) {
/*
* NOTE: Regex explanation
* - /^(git@|https:\/\/)/: This part of the regex specifies that the string must start with either "git@" or "https://".
Expand All @@ -16,5 +16,3 @@ function verifyRemoteOrigin(origin) {
const isOriginRemote = isOriginRemoteRegex.test(origin);
return isOriginRemote;
}

export const verifyHelper = { verifyRemoteOrigin };
2 changes: 1 addition & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { MockRunnerError } from './errors/mock-runner-error.js';
import { main } from './main.js';

try {
await main.run();
await main();
} catch (e) {
if (e instanceof Error) {
const err = new MockRunnerError(e.message, 500, 1, 'Entry point');
Expand Down
19 changes: 10 additions & 9 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import { RC_FILE_NAME } from './helpers/constants.js';
import { Logger } from './helpers/logger.js';
import { messages } from './helpers/messages.js';
import { startMockServer } from './services/start-mock-server.js';
import { userFlowSteps } from './services/user-flow-steps.js';
import { initWithConfigFile } from './services/user-flow-steps/init-with-config-file.js';
import { initWithSchemaPaths } from './services/user-flow-steps/init-with-schema-paths.js';
import { init } from './services/user-flow-steps/init.js';

/**
* @typedef {import('./types/types.d.js').Config} Config
* @typedef {import('./types/types.d.js').Options} Options
Expand All @@ -19,7 +22,7 @@ import { userFlowSteps } from './services/user-flow-steps.js';
* @function run
* @returns {Promise<void>}
*/
const run = async () => {
export const main = async () => {
program
.option('-o, --origin <origin>', 'path or repo containing schemas')
.option('-s, --schema [schemaPaths...]', 'path to schemas')
Expand All @@ -36,23 +39,23 @@ const run = async () => {
Logger.warn(messages.CONFIG_FILE_NOT_FOUND, RC_FILE_NAME);
}
} else if (options?.origin) {
config = await userFlowSteps.init({
config = await init({
origin: options.origin,
schemaPaths: options.schema,
ports: options.port,
});
} else if (options?.schema?.length) {
config = await userFlowSteps.initWithSchemaPaths({
config = await initWithSchemaPaths({
schemaPaths: options.schema,
ports: options.port,
});
} else if (configFileExists) {
config = await userFlowSteps.initWithConfigFile();
config = await initWithConfigFile();
}
if (!config) {
config = await userFlowSteps.init();
config = await init();
}
return startMockServer.run(config.selectedSchemas);
return startMockServer(config.selectedSchemas);
};

/**
Expand All @@ -63,5 +66,3 @@ const run = async () => {
function getConfigFromFile() {
return /** @type {Config} */ (JSON.parse(fs.readFileSync(path.join(process.cwd(), RC_FILE_NAME), 'utf-8'))) || {};
}

export const main = { run };
7 changes: 3 additions & 4 deletions src/services/check-string-in-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,13 @@ import readline from 'node:readline';
* @param {string} filePath - The path to the file.
* @returns {Promise<boolean>} True if the string is in the file, false otherwise.
*/
async function check(stringToCheck, filePath) {
const reader = readline.createInterface({ input: fs.createReadStream(filePath) });
export async function check(stringToCheck, filePath) {
const input = fs.createReadStream(filePath);
const reader = readline.createInterface({ input });
for await (const line of reader) {
if (line === stringToCheck) {
return true;
}
}
return false;
}

export const checkStringInFile = { check };
4 changes: 1 addition & 3 deletions src/services/clone-git-repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import process from 'node:process';
* @param {string} repositoryURL - The URL of the git repository.
* @param {string} dirName - The name of the directory where the repository will be cloned.
*/
function cloneRepository(repositoryURL, dirName) {
export function cloneRepository(repositoryURL, dirName) {
resetDirectory(dirName);
clone(repositoryURL, dirName);
}
Expand Down Expand Up @@ -46,5 +46,3 @@ function clone(repositoryURL, dirName) {
cwd: path.resolve(process.cwd(), dirName), // path to where you want to save the file
});
}

export const git = { cloneRepository };
25 changes: 12 additions & 13 deletions src/services/find-oas-from-dir.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ import { messages } from '../helpers/messages.js';
* @param {string} filePath - The path to the file.
* @returns {Promise<string>} The first line of the file.
*/
async function getFirstLine(filePath) {
const reader = readline.createInterface({ input: fs.createReadStream(filePath) });
const it = reader[Symbol.asyncIterator]();
export async function getFirstLine(filePath) {
const input = fs.createReadStream(filePath);
const reader = readline.createInterface({ input });
const iterator = reader[Symbol.asyncIterator]();
/** @type {IteratorResult<string, string>} */
const line = await it.next();
const line = await iterator.next();
return line.value;
}

Expand All @@ -27,8 +28,8 @@ async function getFirstLine(filePath) {
* @param {string} filePath - The path to the file.
* @returns {Promise<boolean>} True if the file is an OpenAPI specification, false otherwise.
*/
async function isOas(filePath) {
const firstLine = await oas.getFirstLine(filePath);
export async function isOas(filePath) {
const firstLine = await getFirstLine(filePath);
const oasRegEx = /^openapi/i;
return oasRegEx.test(firstLine);
}
Expand All @@ -40,7 +41,7 @@ async function isOas(filePath) {
* @param {string} startPath - The path to the directory.
* @returns {Promise<OasFile[]>} An array of OpenAPI specifications.
*/
const findOasFromDir = async (startPath) => {
export const findOasFromDir = async (startPath) => {
if (!fs.existsSync(startPath)) {
Logger.warn(messages.DIRECTORY_NOT_FOUND, startPath);
return [];
Expand All @@ -52,7 +53,7 @@ const findOasFromDir = async (startPath) => {

for (const file of files) {
const filePath = path.join(startPath, file);
if ((file.endsWith('.yaml') || file.endsWith('.yml')) && (await oas.isOas(filePath))) {
if ((file.endsWith('.yaml') || file.endsWith('.yml')) && (await isOas(filePath))) {
oasFiles.push({
fileName: file,
path: startPath,
Expand All @@ -71,7 +72,7 @@ const findOasFromDir = async (startPath) => {
* @param {OasFile[]} [oasFiles] - An array of OpenAPI specifications.
* @returns {Promise<OasFile[]>} An array of OpenAPI specifications.
*/
const findOasFromDirRecursive = async (startPath, oasFiles = []) => {
export const findOasFromDirRecursive = async (startPath, oasFiles = []) => {
if (!fs.existsSync(startPath)) {
Logger.warn(messages.DIRECTORY_NOT_FOUND, startPath);
return [];
Expand All @@ -84,8 +85,8 @@ const findOasFromDirRecursive = async (startPath, oasFiles = []) => {
const filePath = path.join(startPath, file);
const stat = fs.lstatSync(filePath);
if (stat.isDirectory()) {
await oas.findOasFromDirRecursive(filePath, oasFiles);
} else if ((file.endsWith('.yaml') || file.endsWith('.yml')) && (await oas.isOas(filePath))) {
await findOasFromDirRecursive(filePath, oasFiles);
} else if ((file.endsWith('.yaml') || file.endsWith('.yml')) && (await isOas(filePath))) {
oasFiles.push({
fileName: file,
path: startPath,
Expand All @@ -95,5 +96,3 @@ const findOasFromDirRecursive = async (startPath, oasFiles = []) => {
}
return oasFiles;
};

export const oas = { isOas, getFirstLine, findOasFromDir, findOasFromDirRecursive };
8 changes: 3 additions & 5 deletions src/services/gitignore.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { confirm } from '@inquirer/prompts';
import fs from 'node:fs';
import path from 'node:path';

import { checkStringInFile } from './check-string-in-file.js';
import { check } from './check-string-in-file.js';
import { messages } from '../helpers/messages.js';

export const GITIGNORE_PATH = path.join(process.cwd(), '.gitignore');
Expand All @@ -17,7 +17,7 @@ export const GITIGNORE_PATH = path.join(process.cwd(), '.gitignore');
* @param {string} fileName - The file or folder name to append to .gitignore.
* @returns {Promise<void>}
*/
async function addToGitignore(fileName) {
export async function addToGitignore(fileName) {
const existsGitignoreFile = fs.existsSync(GITIGNORE_PATH);
const isInGitignoreFile = existsGitignoreFile && (await isInGitignore(fileName));
const shouldAddToGitignore = !existsGitignoreFile || !isInGitignoreFile;
Expand All @@ -36,7 +36,7 @@ async function addToGitignore(fileName) {
* @returns {Promise<boolean>} True if the text is in .gitignore, false otherwise.
*/
async function isInGitignore(textToCheck) {
const result = await checkStringInFile.check(textToCheck, GITIGNORE_PATH);
const result = await check(textToCheck, GITIGNORE_PATH);
return result;
}

Expand All @@ -49,5 +49,3 @@ function getLeadingCharacter() {
const lastFileCharacter = fs.readFileSync(GITIGNORE_PATH, 'utf8').slice(-1);
return lastFileCharacter === '\n' ? '' : '\n';
}

export const gitignore = { addToGitignore };
10 changes: 4 additions & 6 deletions src/services/inquirer-validators.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import fs from 'node:fs';

import { validationErrorMessages } from '../helpers/messages.js';
import { verifyHelper } from '../helpers/verify-remote-origin.js';
import { verifyRemoteOrigin } from '../helpers/verify-remote-origin.js';

/**
* @typedef {import('../types/types.d.js').Schema} Schema
Expand All @@ -13,9 +13,9 @@ import { verifyHelper } from '../helpers/verify-remote-origin.js';
* @param {string} value - The value to validate.
* @returns {boolean|string} True if the value is valid, otherwise a string with the error message.
*/
function originValidator(value) {
export function originValidator(value) {
const isLocalPath = fs.existsSync(value);
const isRemoteOrigin = verifyHelper.verifyRemoteOrigin(value);
const isRemoteOrigin = verifyRemoteOrigin(value);
const result = isLocalPath || isRemoteOrigin || validationErrorMessages.origin.INVALID;
return result;
}
Expand All @@ -27,7 +27,7 @@ function originValidator(value) {
* @param {Schema[]} selectedSchemas - The current schema.
* @returns {boolean|string} True if the value is valid, otherwise a string with the error message.
*/
function portValidator(input, selectedSchemas) {
export function portValidator(input, selectedSchemas) {
const numericInput = Number(input);
const isInteger = Number.isInteger(numericInput);
if (!isInteger || numericInput < 0 || numericInput > 65535) {
Expand All @@ -39,5 +39,3 @@ function portValidator(input, selectedSchemas) {
}
return true;
}

export const inquirerValidators = { originValidator, portValidator };
8 changes: 3 additions & 5 deletions src/services/start-mock-server.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import OpenApiMocker from '@sngular/open-api-mocker';
import fs from 'node:fs';

import { userFlowSteps } from './user-flow-steps.js';
import { init } from './user-flow-steps/init.js';
import { Logger } from '../helpers/logger.js';
import { messages } from '../helpers/messages.js';

Expand All @@ -17,7 +17,7 @@ import { messages } from '../helpers/messages.js';
* @param {Schema[]} schemas - An array of schemas.
* @returns {Promise<void>}
*/
async function run(schemas) {
export async function startMockServer(schemas) {
const validatedSchemas = await validateSchemas(schemas);
for (const schema of validatedSchemas) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-assignment
Expand Down Expand Up @@ -48,10 +48,8 @@ async function validateSchemas(schemas) {

if (!allSchemasExists) {
Logger.warn(messages.SOME_SCHEMA_DOES_NOT_EXIST);
const config = await userFlowSteps.init();
const config = await init();
return config.selectedSchemas;
}
return schemas;
}

export const startMockServer = { run };
Loading

0 comments on commit a9b12a1

Please sign in to comment.