Skip to content

Commit

Permalink
Cleaner Errors with Codes and Messages (#24)
Browse files Browse the repository at this point in the history
* Cleaner Errors with Codes and Messages

* reject in place

* use built in 500 error

* rename build workflow to test

* fix errors and eslint

* delete folder

* eslint examples
  • Loading branch information
vvillait88 authored May 2, 2022
1 parent 78c4144 commit 8edf56f
Show file tree
Hide file tree
Showing 14 changed files with 304 additions and 121 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/publish.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ on:
types: [published]

jobs:
build:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
Expand All @@ -18,7 +18,7 @@ jobs:
PDL_API_KEY: ${{secrets.PDL_API_KEY}}

publish-npm:
needs: build
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: Test Package
on: [pull_request]

jobs:
build:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
Expand Down
2 changes: 2 additions & 0 deletions example/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* eslint no-console: "off" */

import dotenv from 'dotenv';

import PDLJS from 'peopledatalabs';
Expand Down
5 changes: 3 additions & 2 deletions example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
},
"author": "People Data Labs",
"license": "MIT",
"devDependencies": {
"dotenv": "^14.2.0"
"dependencies": {
"dotenv": "^14.2.0",
"peopledatalabs": "*"
}
}
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "peopledatalabs",
"version": "3.0.0",
"version": "3.1.0",
"description": "JavaScript client with TypeScript support for the People Data Labs API",
"type": "module",
"main": "dist/index.cjs",
Expand All @@ -10,9 +10,9 @@
"source": "src/index.ts",
"scripts": {
"build": "rm -rf dist && microbundle",
"dev": "microbundle watch",
"dev": "microbundle watch -p 6008",
"test": "yarn run build && yarn run mocha",
"mocha": "mocha --recursive './tests/**/*.js'",
"mocha": "mocha --recursive 'tests/**/*.js'",
"pub": "yarn run build && yarn publish"
},
"repository": {
Expand Down Expand Up @@ -54,7 +54,7 @@
"eslint-plugin-unused-imports": "^2.0.0",
"esm": "^3.2.25",
"microbundle": "^0.14.2",
"mocha": "^9.2.2",
"mocha": "^10.0.0",
"typescript": "^4.6.3"
},
"dependencies": {
Expand Down
2 changes: 1 addition & 1 deletion src/endpoints/autocomplete/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,6 @@ export default (
reject(errorHandler(error));
});
}).catch((error) => {
reject(error.message);
reject(error);
});
});
2 changes: 1 addition & 1 deletion src/endpoints/cleaner/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,6 @@ export default <T, K extends BaseResponse> (
reject(errorHandler(error));
});
}).catch((error) => {
reject(error.message);
reject(error);
});
});
2 changes: 1 addition & 1 deletion src/endpoints/enrichment/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,6 @@ export default <T, K extends BaseResponse>(
reject(errorHandler(error));
});
}).catch((error) => {
reject(error.message);
reject(error);
});
});
4 changes: 2 additions & 2 deletions src/endpoints/retrieve/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default (
apiKey: string,
params: RetrieveParams,
) => new Promise<RetrieveResponse>((resolve, reject) => {
check(params.id, basePath, apiKey, 'ID', 'retrieve').then(() => {
check(params, basePath, apiKey, 'ID', 'retrieve').then(() => {
const headers = {
'Accept-Encoding': 'gzip',
};
Expand All @@ -29,6 +29,6 @@ export default (
reject(errorHandler(error));
});
}).catch((error) => {
reject(error.message);
reject(error);
});
});
2 changes: 1 addition & 1 deletion src/endpoints/search/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,6 @@ export default <T extends BaseSearchParams, K extends BaseResponse>(
reject(errorHandler(error));
});
}).catch((error) => {
reject(error.message);
reject(error);
});
});
75 changes: 55 additions & 20 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { AxiosError } from 'axios';
import { ErrorEndpoint } from './types/error-types';
import { BaseSearchParams } from './types/search-types';
import { AutoCompleteParams } from './types/autocomplete-types';
import { RetrieveParams } from './types/retrieve-types';

const check = (
params: unknown,
Expand All @@ -10,51 +11,85 @@ const check = (
type: string | null,
endpoint: ErrorEndpoint,
) => new Promise<void>((resolve, reject) => {
if (!params) reject(new Error(`Missing ${type || 'Params'}`));
const error: { message?: string, status?: number } = { };

if (!params) {
error.message = `Missing ${type || 'Params'}`;
error.status = 400;
reject(error);
}

if (endpoint === 'search') {
const { searchQuery } = params as BaseSearchParams;
if (!searchQuery) {
reject(new Error('Missing searchQuery'));
error.message = 'Missing searchQuery';
error.status = 400;
reject(error);
}
}

if (endpoint === 'retrieve') {
const { id } = params as RetrieveParams;
if (!id) {
error.message = 'Missing id';
error.status = 400;
reject(error);
}
}

if (endpoint === 'autocomplete') {
const { field } = params as AutoCompleteParams;
const validFields = ['company', 'country', 'industry', 'location', 'major', 'region', 'role', 'school', 'sub_role', 'skill', 'title'];
if (!field) {
reject(new Error('Missing field'));
error.message = 'Missing field';
error.status = 400;
reject(error);
} else if (validFields.indexOf(field) === -1) {
reject(new Error(`field should be one of: ${validFields}`));
error.message = `field should be one of: ${validFields}`;
error.status = 400;
reject(error);
}
}
if (!basePath) reject(new Error('Invalid API Base Path'));
if (!apiKey || apiKey.length !== 64) reject(new Error('Invalid API Key'));

if (!basePath) {
error.message = 'Missing API Base Path';
error.status = 400;
reject(error);
}

if (!apiKey || apiKey.length !== 64) {
error.message = 'Invalid API Key';
error.status = 401;
reject(error);
}

resolve();
});

const errorHandler = (error: AxiosError) => {
const errorMessages = {
400: 'Request contained either missing or invalid parameters',
401: 'Request contained a missing or invalid key',
402: 'Payment Required, You have hit your account maximum (all matches used)',
404: 'No records were found matching your request',
405: 'Request method is not allowed on the requested resource',
429: 'An error occurred due to requests hitting the API too quick',
500: 'The server encountered an unexpected condition which prevented it from fulfilling the request',
};

if (error.response) {
const { status } = error.response;

const errorMessages = {
400: 'Request contained either missing or invalid parameters',
401: 'Request contained a missing or invalid key',
402: 'Payment Required, You have hit your account maximum (all matches used)',
404: 'No records were found matching your request',
405: 'Request method is not allowed on the requested resource',
429: 'An error occurred due to requests hitting the API too quick',
500: 'The server encountered an unexpected condition which prevented it from fulfilling the request',
};
const statusCode = status >= 500 && status < 600 ? 500 : status;

return ({
status: status >= 500 && status < 600 ? 500 : status,
// eslint-disable-next-line max-len
message: errorMessages[status >= 500 && status < 600 ? 500 : status as keyof typeof errorMessages],
status: statusCode,
message: errorMessages[statusCode as keyof typeof errorMessages],
});
}

return ({
status: 500,
message: error.message,
message: errorMessages[500],
});
};

Expand Down
Loading

0 comments on commit 8edf56f

Please sign in to comment.