Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: next versions #532

Merged
merged 2 commits into from
Aug 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/smart-poems-confess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@httpx/dsn-parser': minor
---

Lint with typescript-eslint v6, change || to ??.
7 changes: 7 additions & 0 deletions .changeset/tall-rice-taste.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@httpx/dsn-parser': minor
'@httpx/exception': minor
'@httpx/json-api': minor
---

Lint with typescript/eslint v6 strict
5 changes: 5 additions & 0 deletions .changeset/tricky-jeans-wash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@httpx/dsn-parser': minor
---

Narrow HttpStatusCode type from number to registered status codes (400,...,599)
1 change: 1 addition & 0 deletions examples/nextjs-app/.eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ module.exports = {
],
rules: {
// optional overrides per project
'@typescript-eslint/require-await': 'off',
},
overrides: [
// optional overrides per project file match
Expand Down
14 changes: 7 additions & 7 deletions examples/nextjs-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,21 @@
"@httpx/exception": "workspace:^",
"axios": "1.4.0",
"ky": "0.33.3",
"next": "13.4.12",
"pino": "8.14.2",
"next": "13.4.13",
"pino": "8.15.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"superjson": "1.13.1",
"zod": "3.21.4"
},
"devDependencies": {
"@belgattitude/eslint-config-bases": "1.39.0",
"@types/node": "20.4.5",
"@types/react": "18.2.18",
"@belgattitude/eslint-config-bases": "2.1.0",
"@types/node": "20.4.10",
"@types/react": "18.2.20",
"@types/react-dom": "18.2.7",
"cross-env": "7.0.3",
"eslint": "8.46.0",
"eslint-config-next": "13.4.12",
"eslint": "8.47.0",
"eslint-config-next": "13.4.13",
"postcss": "8.4.27",
"rimraf": "5.0.1",
"tailwindcss": "3.3.3",
Expand Down
10 changes: 5 additions & 5 deletions examples/nextjs-app/src/backend/parseRequestWithZod.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { IncomingMessage } from 'node:http';
import type { HttpException } from '@httpx/exception';
import { HttpBadRequest } from '@httpx/exception';
import { HttpBadRequest, type HttpException } from '@httpx/exception';
import type { NextApiRequest } from 'next';
import type { z, ZodSchema } from 'zod';

Expand All @@ -25,11 +24,12 @@ export const parseRequestWithZod = <
const { onError } = params ?? {};
const parsed = schema.safeParse(req);
if (!parsed.success) {
const { error } = parsed;
const error = parsed.error as unknown as z.ZodError<T>;
if (onError) {
throw onError(error);
}
const msg = parsed.error.errors
const msg = error.errors
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
.map((err) => `${err.path} - ${err.code}`)
.join(', ');

Expand All @@ -38,5 +38,5 @@ export const parseRequestWithZod = <
url: req.url,
});
}
return parsed.data;
return parsed.data as unknown as T;
};
6 changes: 2 additions & 4 deletions examples/nextjs-app/src/backend/withApiErrorHandler.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import type { HttpException } from '@httpx/exception';
import { isHttpException } from '@httpx/exception';
import { isHttpException, type HttpException } from '@httpx/exception';
import { convertToSerializable } from '@httpx/exception/serializer';
import type { NextApiHandler, NextApiRequest, NextApiResponse } from 'next';
import type { LoggerInterface } from '@/lib';
import { ConsoleLogger } from '@/lib';
import { ConsoleLogger, type LoggerInterface } from '@/lib';

type Params = {
logger?: LoggerInterface;
Expand Down
3 changes: 1 addition & 2 deletions examples/nextjs-app/src/lib/zod.utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { ZodTypeAny } from 'zod';
import { z } from 'zod';
import { z, type ZodTypeAny } from 'zod';

export const zodStringToInt = (schema: ZodTypeAny) =>
z.preprocess((v): number | undefined => {
Expand Down
7 changes: 5 additions & 2 deletions examples/nextjs-app/src/pages/api/status/[statusCode].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ import { createHttpException, isHttpErrorStatusCode } from '@httpx/exception';
import type { NextApiHandler } from 'next';
import { z } from 'zod';
import { parseRequestWithZod, withApiErrorHandler } from '@/backend';
import { zodStringToInt, ConsoleLogger } from '@/lib';
import { ConsoleLogger } from '@/lib';

/** Example of zod schema */
const reqSchema = z.object({
method: z.enum(['GET']),
query: z.object({
statusCode: zodStringToInt(z.number().min(100).max(599)),
statusCode: z
.string()
.transform((s) => parseInt(s, 10))
.pipe(z.number().min(100).max(599)),
}),
});

Expand Down
8 changes: 6 additions & 2 deletions examples/nextjs-app/src/pages/getServerSideProps.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import type { HttpException } from '@httpx/exception';
import { HttpNotFound, HttpRequestTimeout } from '@httpx/exception';
import {
HttpNotFound,
HttpRequestTimeout,
type HttpException,
} from '@httpx/exception';
import { fromJson, toJson } from '@httpx/exception/serializer';
import type { GetServerSideProps, InferGetServerSidePropsType } from 'next';
import { Scenarios } from '../components/Scenarios';
Expand Down Expand Up @@ -38,6 +41,7 @@ export default function ssrRoute(

const fetchApiDataAlwaysRequestTimeout = async (): Promise<
Props['apiData']
// eslint-disable-next-line @typescript-eslint/require-await
> => {
throw new HttpRequestTimeout({
message: 'Fake request timeout',
Expand Down
11 changes: 8 additions & 3 deletions examples/nextjs-app/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,19 @@
"esModuleInterop": true,
"resolveJsonModule": true
},
"exclude": ["**/node_modules", "**/.*/*"],
"include": [
".eslintrc.*",
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
"**/*.js",
"**/*.jsx",
"**/*.cjs",
"**/*.mjs"
],
"exclude": ["**/node_modules", "**/.*/"]
"**/*.mjs",
"**/*.json",
".next/types/**/*.ts",
".storybook/**/*.ts",
".storybook/**/*.tsx"
]
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
],
"packageManager": "[email protected]",
"devDependencies": {
"@belgattitude/eslint-config-bases": "1.39.0",
"@belgattitude/eslint-config-bases": "2.1.0",
"@changesets/changelog-github": "0.4.8",
"@changesets/cli": "2.26.2",
"@commitlint/cli": "17.7.1",
Expand All @@ -63,7 +63,7 @@
"cross-env": "7.0.3",
"docsify": "4.13.1",
"docsify-cli": "4.4.4",
"eslint": "8.46.0",
"eslint": "8.47.0",
"husky": "8.0.3",
"is-ci": "3.0.1",
"lint-staged": "13.2.3",
Expand Down
1 change: 1 addition & 0 deletions packages/dsn-parser/.eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const {

module.exports = {
root: true,
parser: '@typescript-eslint/parser',
parserOptions: {
tsconfigRootDir: __dirname,
project: 'tsconfig.json',
Expand Down
4 changes: 2 additions & 2 deletions packages/dsn-parser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,15 @@
},
"devDependencies": {
"@arethetypeswrong/cli": "0.7.1",
"@belgattitude/eslint-config-bases": "1.39.0",
"@belgattitude/eslint-config-bases": "2.1.0",
"@size-limit/file": "8.2.6",
"@types/jest": "29.5.3",
"@vitest/coverage-istanbul": "0.34.1",
"@vitest/ui": "0.34.1",
"browserslist-to-esbuild": "1.2.0",
"cross-env": "7.0.3",
"es-check": "7.1.1",
"eslint": "8.46.0",
"eslint": "8.47.0",
"get-tsconfig": "4.7.0",
"npm-run-all": "4.1.5",
"publint": "0.2.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/dsn-parser/src/assert-parsable-dsn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ export const assertParsableDsn = (
): asserts dsn is ParsableDsn => {
const parsed = parseDsn(dsn as string);
if (!parsed.success) {
throw new Error(msg || `${parsed.message} (${parsed.reason})`);
throw new Error(msg ?? `${parsed.message} (${parsed.reason})`);
}
};
20 changes: 11 additions & 9 deletions packages/dsn-parser/src/dsn-parser.util.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import type {
ParsedDsn,
ParseDsnOptions,
ErrorReasons,
ParserErrorResult,
import {
errorReasons,
type ParsedDsn,
type ParseDsnOptions,
type ErrorReasons,
type ParserErrorResult,
} from './dsn-parser.type';
import { errorReasons } from './dsn-parser.type';

export const createErrorResult = (
reason: ErrorReasons,
Expand All @@ -13,7 +13,7 @@ export const createErrorResult = (
return {
success: false,
reason: reason,
message: msg || errorReasons[reason],
message: msg ?? errorReasons[reason],
};
};

Expand All @@ -28,7 +28,9 @@ export const isParsableNumber = (value: unknown): value is number => {
return typeof value === 'string' && /^-?\d{1,16}$/.test(value);
};

export const isValidNetworkPort = (port: number): port is number => {
type ValidNetworkPort = number;

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

Expand All @@ -51,6 +53,6 @@ export const mergeDsnOverrides = (
merged[key] =
key in overrides ? (overrides as Record<string, unknown>)[key] : value;
});
merged['params'] = params;
merged.params = params;
return merged as unknown as ParsedDsn;
};
16 changes: 10 additions & 6 deletions packages/dsn-parser/src/parse-dsn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
import { parseQueryParams } from './query-param-parser';

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

const defaultOptions = {
Expand All @@ -29,24 +30,24 @@ export const parseDsn = (
typeof dsn !== 'string' ? 'INVALID_ARGUMENT' : 'EMPTY_DSN'
);
}
const opts = { ...defaultOptions, ...(options || {}) };
const opts = { ...defaultOptions, ...(options ?? {}) };
const { overrides = {}, lowercaseDriver } = opts;
const matches = dsn.match(dsnRegexp);
if (matches === null || !matches.groups) {
if (!matches?.groups) {
return createErrorResult('PARSE_ERROR');
}
const parsed: Record<string, unknown> = {};
Object.entries(matches.groups).forEach(([key, value]) => {
if (typeof value === 'string') {
switch (key) {
case 'driver':
parsed['driver'] = lowercaseDriver ? value.toLowerCase() : value;
parsed.driver = lowercaseDriver ? value.toLowerCase() : value;
break;
case 'port':
parsed['port'] = Number.parseInt(value, 10);
parsed.port = Number.parseInt(value, 10);
break;
case 'params':
parsed['params'] = parseQueryParams(value);
parsed.params = parseQueryParams(value);
break;
default:
parsed[key] = value;
Expand All @@ -57,7 +58,10 @@ export const parseDsn = (
mergeDsnOverrides(parsed as ParsedDsn, overrides)
) as ParsedDsn;
if (val?.port && !isValidNetworkPort(val.port)) {
return createErrorResult('INVALID_PORT', `Invalid port: ${val.port}`);
return createErrorResult(
'INVALID_PORT',
`Invalid port: ${val.port as unknown as number}`
);
}
return {
success: true,
Expand Down
2 changes: 1 addition & 1 deletion 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, string | boolean | number | null> => {
const { parseBooleans, setTrueForUndefinedValues, parseNumbers } = {
...defaultOptions,
...(options || {}),
...(options ?? {}),
};
const defaultValue = setTrueForUndefinedValues ? true : null;
const parts = queryParams.split('&').filter((v) => v.trim().length > 0);
Expand Down
13 changes: 12 additions & 1 deletion packages/dsn-parser/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,16 @@
"strict": true,
"paths": {},
"types": ["vitest/globals"]
}
},
"exclude": ["**/node_modules", "**/.*/*", "dist", "coverage"],
"include": [
".eslintrc.*",
"**/*.ts",
"**/*.tsx",
"**/*.js",
"**/*.jsx",
"**/*.cjs",
"**/*.mjs",
"**/*.json"
]
}
1 change: 1 addition & 0 deletions packages/exception/.eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const {

module.exports = {
root: true,
parser: '@typescript-eslint/parser',
parserOptions: {
tsconfigRootDir: __dirname,
project: 'tsconfig.json',
Expand Down
8 changes: 4 additions & 4 deletions packages/exception/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -99,21 +99,21 @@
},
"devDependencies": {
"@arethetypeswrong/cli": "0.7.1",
"@belgattitude/eslint-config-bases": "1.39.0",
"@belgattitude/eslint-config-bases": "2.1.0",
"@size-limit/file": "8.2.6",
"@size-limit/webpack": "8.2.6",
"@size-limit/webpack-why": "8.2.6",
"@swc/core": "1.3.75",
"@swc/core": "1.3.76",
"@types/jest": "29.5.3",
"@types/node": "20.4.9",
"@types/node": "20.4.10",
"@types/statuses": "2.0.1",
"@vitest/coverage-istanbul": "0.34.1",
"@vitest/ui": "0.34.1",
"browserslist-to-esbuild": "1.2.0",
"cross-env": "7.0.3",
"error-cause-polyfill": "2.0.0",
"es-check": "7.1.1",
"eslint": "8.46.0",
"eslint": "8.47.0",
"get-tsconfig": "4.7.0",
"jest": "29.6.2",
"npm-run-all": "4.1.5",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ describe('HttpClientException', () => {
throw errorCause;
} catch (cause) {
exception = new HttpClientException(500, {
cause: cause as unknown as Error,
cause: cause as Error,
});
}
expect(exception.cause).toStrictEqual(errorCause);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ describe('HttpException', () => {
throw errorCause;
} catch (cause) {
exception = new HttpException(500, {
cause: cause as unknown as Error,
cause: cause as Error,
});
}
expect(exception.cause).toStrictEqual(errorCause);
Expand Down
Loading