Skip to content

Commit

Permalink
feat: minor code optimizations with unicorn plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
belgattitude committed Nov 18, 2023
1 parent fabac5e commit ec2ac22
Show file tree
Hide file tree
Showing 26 changed files with 220 additions and 147 deletions.
5 changes: 5 additions & 0 deletions .changeset/four-hotels-breathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@httpx/json-api': patch
---

Optimize code thanks to eslint unicorn plugin
5 changes: 5 additions & 0 deletions .changeset/rotten-beers-compare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@httpx/exception': patch
---

Optimize code thanks to eslint unicorn plugin
5 changes: 5 additions & 0 deletions .changeset/shaggy-crabs-dream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@httpx/dsn-parser': patch
---

Optimize code thanks to eslint unicorn plugin
4 changes: 1 addition & 3 deletions examples/nextjs-app/next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ const NEXTJS_IGNORE_TYPECHECK = trueEnv.includes(
process.env?.NEXTJS_IGNORE_TYPECHECK ?? 'false'
);

const TYPESCRIPT_CONFIG = process.env.TSCONFIG
? process.env.TSCONFIG
: './tsconfig.json';
const TYPESCRIPT_CONFIG = process.env.TSCONFIG ?? './tsconfig.json';

/** @type {import('next').NextConfig} */
const nextConfig = {
Expand Down
4 changes: 2 additions & 2 deletions examples/nextjs-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@
"zod": "3.22.4"
},
"devDependencies": {
"@belgattitude/eslint-config-bases": "3.5.0",
"@belgattitude/eslint-config-bases": "4.0.1",
"@types/node": "20.9.1",
"@types/react": "18.2.37",
"@types/react-dom": "18.2.15",
"cross-env": "7.0.3",
"eslint": "8.53.0",
"eslint": "8.54.0",
"eslint-config-next": "14.0.3",
"postcss": "8.4.31",
"rimraf": "5.0.5",
Expand Down
2 changes: 1 addition & 1 deletion examples/nextjs-app/src/lib/zod.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { type ZodTypeAny, z } from 'zod';
export const zodStringToInt = (schema: ZodTypeAny) =>
z.preprocess((v): number | undefined => {
if (typeof v === 'string') {
return parseInt(v, 10);
return Number.parseInt(v, 10);
}
if (typeof v === 'number') return v;
return undefined;
Expand Down
2 changes: 1 addition & 1 deletion examples/nextjs-app/src/pages/api/status/[statusCode].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const reqSchema = z.object({
query: z.object({
statusCode: z
.string()
.transform((s) => parseInt(s, 10))
.transform((s) => Number.parseInt(s, 10))
.pipe(z.number().min(100).max(599)),
}),
});
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
],
"packageManager": "[email protected]",
"devDependencies": {
"@belgattitude/eslint-config-bases": "3.5.0",
"@belgattitude/eslint-config-bases": "4.0.1",
"@changesets/changelog-github": "0.4.8",
"@changesets/cli": "2.26.2",
"@commitlint/cli": "18.4.2",
Expand Down
5 changes: 4 additions & 1 deletion packages/dsn-parser/.eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ const {
module.exports = {
extends: [
'@belgattitude/eslint-config-bases/typescript',
'@belgattitude/eslint-config-bases/perfectionist',
'@belgattitude/eslint-config-bases/sonar',
'@belgattitude/eslint-config-bases/regexp',
'@belgattitude/eslint-config-bases/jest',
'@belgattitude/eslint-config-bases/perfectionist',
'@belgattitude/eslint-config-bases/performance',

// Apply prettier and disable incompatible rules
'@belgattitude/eslint-config-bases/prettier-plugin',
],
Expand All @@ -38,5 +40,6 @@ module.exports = {
root: true,
rules: {
'sonarjs/cognitive-complexity': ['error', 17],
'unicorn/no-array-reduce': 'off',
},
};
2 changes: 1 addition & 1 deletion packages/dsn-parser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
},
"devDependencies": {
"@arethetypeswrong/cli": "0.13.1",
"@belgattitude/eslint-config-bases": "3.5.0",
"@belgattitude/eslint-config-bases": "4.0.1",
"@size-limit/file": "11.0.0",
"@size-limit/webpack": "11.0.0",
"@vitest/coverage-istanbul": "1.0.0-beta.4",
Expand Down
2 changes: 1 addition & 1 deletion packages/dsn-parser/src/__tests__/dsn-parser.util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ describe('isValidNetworkPort', () => {
it('should work as expected', () => {
expect(isValidNetworkPort(3001)).toBeTruthy();
expect(isValidNetworkPort(0)).toBeFalsy();
expect(isValidNetworkPort(65536)).toBeFalsy();
expect(isValidNetworkPort(65_536)).toBeFalsy();
expect(isValidNetworkPort(-1)).toBeFalsy();
});
});
Expand Down
4 changes: 1 addition & 3 deletions packages/dsn-parser/src/convert-jdbc-to-dsn.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
export const convertJdbcToDsn = (jdbc: string): string => {
const [part1, ...rest] = jdbc.split(';');
return [part1, rest ? rest.join('&') : undefined]
.filter((v) => Boolean(v))
.join('?');
return [part1, rest ? rest.join('&') : undefined].filter(Boolean).join('?');
};
6 changes: 3 additions & 3 deletions packages/dsn-parser/src/dsn-parser.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const isParsableNumber = (value: unknown): value is number => {
type ValidNetworkPort = number;

export const isValidNetworkPort = (port: number): port is ValidNetworkPort => {
return port < 65536 && port > 0;
return port < 65_536 && port > 0;
};

export const removeUndefined = (
Expand All @@ -49,10 +49,10 @@ export const mergeDsnOverrides = (
): ParsedDsn => {
const merged: Record<string, unknown> = {};
const { params, ...restDsn } = parsedDsn;
Object.entries(restDsn).forEach(([key, value]) => {
for (const [key, value] of Object.entries(restDsn)) {
merged[key] =
key in overrides ? (overrides as Record<string, unknown>)[key] : value;
});
}
merged.params = params;
return merged as unknown as ParsedDsn;
};
22 changes: 13 additions & 9 deletions packages/dsn-parser/src/parse-dsn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { parseQueryParams } from './query-param-parser';

const dsnRegexp =
// eslint-disable-next-line regexp/no-unused-capturing-group,regexp/no-misleading-capturing-group
/^(?<driver>([\w+-]{1,40})):\/\/((?<user>[^/:]{1,200})?(:(?<pass>.{0,200}))?@)?(?<host>[^/:]{1,200}?)(:(?<port>\d+)?)?(\/(?<db>([.#@$\w-])+))?(\?(?<params>.{1,1000}))?$/;
/^(?<driver>([\w+-]{1,40})):\/\/((?<user>[^/:]{1,200})?(:(?<pass>.{0,200}))?@)?(?<host>[^/:]{1,200}?)(:(?<port>\d+)?)?(\/(?<db>([\w#$.@-])+))?(\?(?<params>.{1,1000}))?$/;

const defaultOptions = {
lowercaseDriver: false,
Expand All @@ -27,33 +27,37 @@ export const parseDsn = (
): ParserResult => {
if (!isNonEmptyString(dsn)) {
return createErrorResult(
typeof dsn !== 'string' ? 'INVALID_ARGUMENT' : 'EMPTY_DSN'
typeof dsn === 'string' ? 'EMPTY_DSN' : 'INVALID_ARGUMENT'
);
}
const opts = { ...defaultOptions, ...(options ?? {}) };
const opts = { ...defaultOptions, ...options };
const { lowercaseDriver, overrides = {} } = opts;
const matches = dsn.match(dsnRegexp);
if (!matches?.groups) {
return createErrorResult('PARSE_ERROR');
}
const parsed: Record<string, unknown> = {};
Object.entries(matches.groups).forEach(([key, value]) => {
for (const [key, value] of Object.entries(matches.groups)) {
if (typeof value === 'string') {
switch (key) {
case 'driver':
case 'driver': {
parsed.driver = lowercaseDriver ? value.toLowerCase() : value;
break;
case 'port':
}
case 'port': {
parsed.port = Number.parseInt(value, 10);
break;
case 'params':
}
case 'params': {
parsed.params = parseQueryParams(value);
break;
default:
}
default: {
parsed[key] = value;
}
}
}
});
}
const val = removeUndefined(
mergeDsnOverrides(parsed as ParsedDsn, overrides)
) as ParsedDsn;
Expand Down
4 changes: 2 additions & 2 deletions packages/dsn-parser/src/query-param-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const parseQueryParams = (
): Record<string, boolean | null | number | string> => {
const { parseBooleans, parseNumbers, setTrueForUndefinedValues } = {
...defaultOptions,
...(options ?? {}),
...options,
};
const defaultValue = setTrueForUndefinedValues ? true : null;
const parts = queryParams.split('&').filter((v) => v.trim().length > 0);
Expand All @@ -40,6 +40,6 @@ export const parseQueryParams = (
} else {
val = defaultValue;
}
return { ...acc, ...{ [key]: val } };
return { ...acc, [key]: val };
}, {});
};
3 changes: 2 additions & 1 deletion packages/exception/.eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ const {
module.exports = {
extends: [
'@belgattitude/eslint-config-bases/typescript',
'@belgattitude/eslint-config-bases/perfectionist',
'@belgattitude/eslint-config-bases/sonar',
'@belgattitude/eslint-config-bases/regexp',
'@belgattitude/eslint-config-bases/jest',
'@belgattitude/eslint-config-bases/perfectionist',
'@belgattitude/eslint-config-bases/performance',
// Apply prettier and disable incompatible rules
'@belgattitude/eslint-config-bases/prettier-plugin',
],
Expand Down
4 changes: 2 additions & 2 deletions packages/exception/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ Basic usage below, but don't forget to check the
👉 full documentation on [https://belgattitude.github.io/httpx](https://belgattitude.github.io/httpx). 👈.
It includes serialization recipes, http422 with validation issues and more..

### By classname
### By named import

```typescript
import { HttpNotFound, HttpInternalServerError } from '@httpx/exception';
Expand Down Expand Up @@ -86,7 +86,7 @@ const e500 = new HttpInternalServerError({
});
```

### By named import
### By status code

```typescript
import { createHttpException } from '@httpx/exception';
Expand Down
2 changes: 1 addition & 1 deletion packages/exception/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@
},
"devDependencies": {
"@arethetypeswrong/cli": "0.13.1",
"@belgattitude/eslint-config-bases": "3.5.0",
"@belgattitude/eslint-config-bases": "4.0.1",
"@size-limit/file": "11.0.0",
"@size-limit/webpack": "11.0.0",
"@size-limit/webpack-why": "11.0.0",
Expand Down
57 changes: 33 additions & 24 deletions packages/exception/src/serializer/mapper/createFromSerializable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,11 @@ const createCustomError = (
): Error | NativeError => {
const { cause, message, name, stack } = serializable;
const cls = nativeErrorMap[name as keyof typeof nativeErrorMap] ?? Error;
let e: Error | NativeError;
if (cause) {
e = new cls(message, {
cause: createFromSerializable(cause),
});
} else {
e = new cls(message);
}
const e: Error | NativeError = cause
? new cls(message, {
cause: createFromSerializable(cause),
})
: new cls(message);
if (stack) {
e.stack = stack;
}
Expand All @@ -35,24 +32,33 @@ const createCustomError = (
const createHttpExceptionError = (
serializable: SerializableHttpException
): Error | HttpException => {
const { cause, name, stack, statusCode } = serializable;
const {
cause,
name,
stack,
statusCode,
code,
errorId,
message,
method,
url,
issues,
} = serializable;
const params = {
cause: cause ? createFromSerializable(cause) : undefined,
code: serializable.code,
errorId: serializable.errorId,
message: serializable.message,
method: serializable.method,
url: serializable.url,
...(serializable.issues ? { issues: serializable.issues } : {}),
code: code,
errorId: errorId,
message: message,
method: method,
url: url,
...(issues ? { issues } : {}),
};
let e: HttpException;
try {
if (isBaseHttpException(name)) {
e = new baseExceptionMap[name](statusCode, params);
} else {
e = createHttpException(statusCode, params);
}
} catch (e) {
e = isBaseHttpException(name)
? new baseExceptionMap[name](statusCode, params)
: createHttpException(statusCode, params);
} catch {
return createCustomError({ cause, message: params.message, name, stack });
}
if (stack) {
Expand All @@ -72,19 +78,22 @@ export const createFromSerializable = (
): Error | HttpException | NativeError => {
let e: Error | HttpException | NativeError;
switch (payload.__type) {
case 'HttpException':
case 'HttpException': {
e = createHttpExceptionError(payload);
break;
}
case 'NativeError':
case 'NonNativeError':
case 'NonNativeError': {
e = createCustomError(payload);
break;
default:
}
default: {
throw new Error(
`Can't unserialize from unknown error (${
(payload as Serializable).name
})`
);
}
}
return e;
};
1 change: 1 addition & 0 deletions packages/exception/src/support/supportsErrorCause.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export const supportsErrorCause = () => {
const cause = Symbol('');
// eslint-disable-next-line unicorn/error-message
return new Error('', { cause })?.cause === cause;
};
2 changes: 1 addition & 1 deletion packages/exception/src/utils/getMsgFromCls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const getMsgFromCls = (className: string) => {
const preserveName =
className.endsWith('Exception') || className === 'HttpVersionNotSupported';
return (preserveName ? className : className.slice(4))
.replace(splitCapsRegexp, (match) => ` ${match}`)
.replaceAll(splitCapsRegexp, (match) => ` ${match}`)
.trim()
.split(' ')
.map((word, idx) => (idx === 0 ? word : word.toLowerCase()))
Expand Down
6 changes: 3 additions & 3 deletions packages/exception/test/specs/general-specs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ describe('Common specs', () => {
it.each(all)(
'%s(%i) match statuses "%s"',
(className, status, npmStatusMsg) => {
const title = npmStatusMsg.replace(/[\W_]+/g, '').toLowerCase();
const title = npmStatusMsg.replaceAll(/[\W_]+/g, '').toLowerCase();
// eslint-disable-next-line jest/no-conditional-in-test
const expected = title.startsWith('http') ? title : `http${title}`;
expect(className.toLowerCase()).toStrictEqual(expected);
Expand All @@ -36,9 +36,9 @@ describe('Common specs', () => {
it.each(all)(
'should match official npm/statuses messages',
(className, status, npmStatusMsg, exception) => {
const expected = npmStatusMsg.replace(/[\W_]+/g, '').toLowerCase();
const expected = npmStatusMsg.replaceAll(/[\W_]+/g, '').toLowerCase();
expect(
exception?.message.toLowerCase().replace(/[\W_]+/g, '')
exception?.message.toLowerCase().replaceAll(/[\W_]+/g, '')
).toStrictEqual(expected);
}
);
Expand Down
Loading

0 comments on commit ec2ac22

Please sign in to comment.