Skip to content

Commit

Permalink
Convert to new flat config for eslint
Browse files Browse the repository at this point in the history
  • Loading branch information
dpilafian committed Aug 12, 2024
1 parent ca4444e commit e01ea8a
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 48 deletions.
22 changes: 22 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// @ts-check

import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';

export default [
eslint.configs.recommended,
...tseslint.configs.strictTypeChecked,
{ ignores: ['**/*.js'] },
{
languageOptions: { parserOptions: { projectService: true } },
rules: {
'@typescript-eslint/no-confusing-void-expression': 'off', //prefer minimal arrow functions
'@typescript-eslint/no-floating-promises': 'off', //annimations may be fire-and-forget
'@typescript-eslint/no-misused-promises': 'off', //annimations may be fire-and-forget
'@typescript-eslint/no-non-null-assertion': 'off', //ts cannot always know value exists
'@typescript-eslint/restrict-template-expressions': 'off', //numbers in templates are natural
'@typescript-eslint/unbound-method': 'off', //safer to not use 'this'
'@typescript-eslint/use-unknown-in-catch-callback-variable': 'off', //clarity over theoretical exceptions
},
},
];
36 changes: 18 additions & 18 deletions fetch-json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export type FetchJsonInit = { strictErrors: boolean };
export type FetchJsonOptions = RequestInit & Partial<FetchJsonInit>;
export type FetchJsonMethod = string;
export type FetchJsonParams = { [field: string]: string | number | boolean | null | undefined };
export type FetchJsonParsedResponse = Json | any;
//export type FetchJsonParsedResponse = Json | any;
export type FetchJsonAltResponse = { //used when the HTTP response is an error or unexpectedly not JSON
ok: boolean, //code for HTTP status in the range 200-299
error: boolean, //code for HTTP status not in the range 200-299 or exception thrown
Expand All @@ -18,7 +18,7 @@ export type FetchJsonAltResponse = { //used when the HTTP response is an error
data: Json | null, //body of the HTTP responce if the content is JSON
response: Response, //response object
};
export type FetchJsonResponse = FetchJsonParsedResponse | FetchJsonAltResponse;
//export type FetchJsonResponse = FetchJsonParsedResponse | FetchJsonAltResponse;
export type FetchJsonLogger = (
dateIso: string, //timestamp, such as '2022-12-06T07:24:40.330Z'
type?: 'response' | 'request', //message direction
Expand All @@ -41,18 +41,18 @@ const fetchJson = {
this.baseOptions = options;
return this.baseOptions;
},
request<T>(method: FetchJsonMethod, url: string, data?: FetchJsonParams | Json | T,
options?: FetchJsonOptions): Promise<FetchJsonResponse> {
request(method: FetchJsonMethod, url: string, data?: unknown,
options?: FetchJsonOptions): Promise<any> {
const defaults: FetchJsonOptions = {
method: method,
credentials: 'same-origin',
strictErrors: false,
};
const settings = { ...defaults, ...this.baseOptions, ...options };
if (!settings.method || typeof settings.method !== 'string')
throw Error('[fetch-json] HTTP method missing or invalid.');
throw new Error('[fetch-json] HTTP method missing or invalid.');
if (typeof url !== 'string')
throw Error('[fetch-json] URL must be a string.');
throw new Error('[fetch-json] URL must be a string.');
const httpMethod = settings.method.trim().toUpperCase();
const isGetRequest = httpMethod === 'GET';
const jsonHeaders: HeadersInit = { Accept: 'application/json' };
Expand All @@ -65,13 +65,13 @@ const fetchJson = {
const params = () => paramKeys.map(toPair).join('&');
const requestUrl = !paramKeys.length ? url : url + (url.includes('?') ? '&' : '?') + params();
settings.body = !isGetRequest && data ? JSON.stringify(data) : null;
const log = (type: 'response' | 'request', ...items: any[]) => {
const log = (type: 'response' | 'request', ...items: (string | number | boolean | null)[]) => {
const logUrl = url.replace(/[?].*/, ''); //security: prevent logging url parameters
const domain = logUrl.replace(/.*:[/][/]/, '').replace(/[:/].*/, ''); //extract hostname
if (this.logger)
this.logger(new Date().toISOString(), type, httpMethod, domain, logUrl, ...items);
this.logger(new Date().toISOString(), type, httpMethod, domain, logUrl, ...<boolean[]>items);
};
const toJson = (value: unknown): Promise<FetchJsonResponse> => {
const toJson = (value: unknown): Promise<any> => {
const response = <Response>value;
const contentType = response.headers.get('content-type');
const isHead = httpMethod === 'HEAD';
Expand All @@ -86,7 +86,7 @@ const fetchJson = {
data: data ?? null,
response: response,
});
const jsonToObj = (data: Json): FetchJsonResponse =>
const jsonToObj = (data: Json): any =>
response.ok ? data : textToObj(JSON.stringify(data), data);
const errToObj = (error: Error): FetchJsonAltResponse => ({
ok: false,
Expand All @@ -99,30 +99,30 @@ const fetchJson = {
});
log('response', response.ok, response.status, response.statusText, contentType);
if (settings.strictErrors && !response.ok)
throw Error('[fetch-json] HTTP response status ("strictErrors" mode enabled): ' + response.status);
throw new Error(`[fetch-json] HTTP response status ("strictErrors" mode enabled): ${response.status}`);
return isHead ? response.text().then(headersObj) :
isJson ? response.json().then(jsonToObj).catch(errToObj) : response.text().then(textToObj);
};
log('request');
const settingsRequestInit = JSON.parse(JSON.stringify(settings)); //TODO: <RequestInit>
const settingsRequestInit = <RequestInit>JSON.parse(JSON.stringify(settings)); //TODO: <RequestInit>
return fetch(requestUrl, settingsRequestInit).then(toJson);
},
get(url: string, params?: FetchJsonParams, options?: FetchJsonOptions): Promise<FetchJsonResponse> {
get(url: string, params?: FetchJsonParams, options?: FetchJsonOptions): Promise<any> {
return this.request('GET', url, params, options);
},
post<T>(url: string, resource?: Json | T, options?: FetchJsonOptions): Promise<FetchJsonResponse> {
post(url: string, resource?: unknown, options?: FetchJsonOptions): Promise<any> {
return this.request('POST', url, resource, options);
},
put<T>(url: string, resource?: Json | T, options?: FetchJsonOptions): Promise<FetchJsonResponse> {
put(url: string, resource?: unknown, options?: FetchJsonOptions): Promise<any> {
return this.request('PUT', url, resource, options);
},
patch<T>(url: string, resource?: Json | T, options?: FetchJsonOptions): Promise<FetchJsonResponse> {
patch(url: string, resource?: unknown, options?: FetchJsonOptions): Promise<any> {
return this.request('PATCH', url, resource, options);
},
delete<T>(url: string, resource?: Json | T, options?: FetchJsonOptions): Promise<FetchJsonResponse> {
delete(url: string, resource?: unknown, options?: FetchJsonOptions): Promise<any> {
return this.request('DELETE', url, resource, options);
},
head(url: string, params?: FetchJsonParams, options?: FetchJsonOptions): Promise<FetchJsonResponse> {
head(url: string, params?: FetchJsonParams, options?: FetchJsonOptions): Promise<any> {
return this.request('HEAD', url, params, options);
},
logger: <FetchJsonLogger | null>null,
Expand Down
42 changes: 12 additions & 30 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,32 +46,13 @@
"fetch": true
}
},
"eslintConfig": {
"ignorePatterns": [
"build",
"dist",
"node_modules"
],
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"@typescript-eslint/no-non-null-assertion": "off"
}
},
"runScriptsConfig": {
"clean": [
"rimraf build dist"
],
"lint": [
"jshint . --exclude-path .gitignore",
"eslint --max-warnings 0 . --ext .ts"
"eslint --max-warnings 0"
],
"build": [
"tsc",
Expand All @@ -91,28 +72,29 @@
"interactive": "http-server -o spec/fixtures/"
},
"devDependencies": {
"@eslint/js": "~9.6",
"@fortawesome/fontawesome-free": "~6.5",
"@types/node": "~20.14",
"@eslint/js": "~9.9",
"@fortawesome/fontawesome-free": "~6.6",
"@types/eslint__js": "~8.42",
"@types/node": "~22.2",
"add-dist-header": "~1.4",
"assert-deep-strict-equal": "~1.2",
"copy-file-util": "~1.2",
"copy-folder-util": "~1.1",
"dna-engine": "~3.2",
"eslint": "8.57.0",
"eslint": "~9.9",
"esm-to-plain-js": "~1.1",
"http-server": "~14.1",
"jsdom": "~24.1",
"jshint": "~2.13",
"mocha": "~10.5",
"puppeteer": "~22.12",
"mocha": "~10.7",
"puppeteer": "~23.0",
"puppeteer-browser-ready": "~1.3",
"replacer-util": "~1.3",
"rimraf": "~5.0",
"run-scripts-util": "~1.2",
"rimraf": "~6.0",
"run-scripts-util": "~1.3",
"typescript": "~5.5",
"typescript-eslint": "~7.14",
"uglify-js": "~3.18",
"typescript-eslint": "~8.0",
"uglify-js": "~3.19",
"w3c-html-validator": "~1.8",
"web-ignition": "~2.2",
"whatwg-fetch": "~3.6"
Expand Down

0 comments on commit e01ea8a

Please sign in to comment.