Skip to content

Commit

Permalink
Merge pull request #68 from fecgov/feature/189-npm-integration
Browse files Browse the repository at this point in the history
Fix linting and some empty array logic
  • Loading branch information
mjtravers authored Apr 25, 2022
2 parents f096876 + b1b4908 commit b4ea8be
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 10 deletions.
21 changes: 11 additions & 10 deletions fecfile_validate_js/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,14 @@ const ajv = new Ajv({ allErrors: true, strictSchema: false });
* @returns {ValidationError[]} Modified version of Ajv output, empty array if no errors found
*/
export function validate(schema: any, data: any, fieldsToValidate: string[] = []): ValidationError[] {
const theSchemaUrl = schema['$schema'];
schema['$schema'] = theSchemaUrl.replace('https', 'http');

const validator: ValidateFunction = ajv.compile(schema);
const isValid: boolean = validator(data);
const errors: ValidationError[] = [];

if (!isValid && !!validator.errors) {
if (!isValid && !!validator.errors?.length) {
validator.errors.forEach((error) => {
const parsedError = parseError(error)
if (!fieldsToValidate.length || fieldsToValidate.includes(parsedError.path)){
const parsedError = parseError(error);
if (!fieldsToValidate.length || fieldsToValidate.includes(parsedError.path)) {
errors.push(parsedError);
}
});
Expand All @@ -54,16 +51,20 @@ export function validate(schema: any, data: any, fieldsToValidate: string[] = []
return errors;
}

/**
* Format error message from Ajv into our ValidationError interface
* @param {ErrorObject} error - Ajv ErrorObject interface
* @returns {ValidationError}
*/
function parseError(error: ErrorObject): ValidationError {
let path = error.instancePath.substring(1)
if (error.keyword == "required") {
let path = error.instancePath.substring(1);
if (error.keyword == 'required') {
path = error.params.missingProperty;
}
return {
path: path,
keyword: error.keyword,
params: error.params,
message: !!error.message ? error.message : null,
}
};
}

12 changes: 12 additions & 0 deletions fecfile_validate_js/tests/candidate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,18 @@ Deno.test({
},
});

Deno.test({
name: 'it should fail with for candidate office S with an invalid candidate state format',
fn: () => {
const testData = { ...data };
testData.candidate_office = 'S';
testData.candidate_state = 'M1';
const result = validate(candidateContactSchema, testData);
assertEquals(result[0].path, 'candidate_state');
assertEquals(result[0].message, 'must match pattern "^[A-Z]{2}$"');
},
});

Deno.test({
name: 'it should pass with for candidate office S with a candidate state',
fn: () => {
Expand Down

0 comments on commit b4ea8be

Please sign in to comment.