Skip to content

Commit

Permalink
refactor(dredge-route, dredge-types)!: queries is replace with params
Browse files Browse the repository at this point in the history
params and queries are now the same thing
  • Loading branch information
dhrjarun committed Dec 25, 2024
1 parent 53ab51e commit abdcb13
Show file tree
Hide file tree
Showing 34 changed files with 473 additions and 619 deletions.
23 changes: 9 additions & 14 deletions packages/adapters/source/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import {
MimeStore,
deserializeParams as defaultDeserializeParams,
deserializeQueries as defaultDeserializeQueries,
defaultJSONBodyParser,
defaultJsonDataSerializer,
defaultTextBodyParser,
defaultTextDataSerializer,
searchParamsToObject,
searchParamsToDredgeParams,
trimSlashes,
} from "dredge-common";
import { RawRequest, getPathParams } from "dredge-route";
import { getPathParams } from "dredge-route";
import type { DredgeRouter } from "dredge-types";
import { MaybePromise } from "dredge-types";
import { ReadableStream } from "stream/web";
import { RawRequest } from "dredge-types";

// TODO: add bodyUsed getter
type BodyParserFunction = (options: {
Expand Down Expand Up @@ -41,14 +41,10 @@ export interface CreateFetchRequestHandlerOptions<State extends object> {
dataSerializers?: {
[key: string]: DataSerializerFunction;
};
deserializeQueries?: (
queries: Record<string, string[]>,
schema: Record<string, any>,
) => Record<string, any[]>;
deserializeParams?: (
params: Record<string, string>,
params: Record<string, string | string[]>,
schema: Record<string, any>,
) => Record<string, any>;
) => Record<string, any | any[]>;
}

export function createFetchRequestHandler<Context extends object = {}>(
Expand All @@ -59,7 +55,6 @@ export function createFetchRequestHandler<Context extends object = {}>(
state = {},
prefixUrl,
deserializeParams = defaultDeserializeParams,
deserializeQueries = defaultDeserializeQueries,
} = options;

const parsedPrefixUrl = new URL(prefixUrl || "relative:///", "relative:///");
Expand Down Expand Up @@ -93,18 +88,18 @@ export function createFetchRequestHandler<Context extends object = {}>(
const schema = route._schema;

const headers = Object.fromEntries(req.headers);
const params = getPathParams(schema.paths)(pathArray);
const queries = searchParamsToObject(url.search);
const params = {
...getPathParams(schema.paths)(pathArray),
...searchParamsToDredgeParams(url.search),
};

const parsedParams = deserializeParams(params, schema.params);
const parsedQueries = deserializeQueries(queries, schema.queries);

const middlewareRequest: RawRequest = {
url: url.href,
method: req.method || "get",
headers,
params: parsedParams,
queries: parsedQueries,
data: undefined,
};

Expand Down
22 changes: 8 additions & 14 deletions packages/adapters/source/node-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,17 @@ import { Readable, Stream } from "stream";
import {
MimeStore,
deserializeParams as defaultDeserializeParams,
deserializeQueries as defaultDeserializeQueries,
defaultJSONBodyParser,
defaultJsonDataSerializer,
defaultTextBodyParser,
defaultTextDataSerializer,
joinDuplicateHeaders,
searchParamsToObject,
searchParamsToDredgeParams,
trimSlashes,
} from "dredge-common";
import { getPathParams, RawRequest } from "dredge-route";
import { getPathParams } from "dredge-route";
import type { DredgeRouter } from "dredge-types";
import { MaybePromise } from "dredge-types";
import { MaybePromise, RawRequest } from "dredge-types";
import parseUrl from "parseurl";

// TODO: add bodyUsed getter
Expand Down Expand Up @@ -42,12 +41,8 @@ export interface CreateNodeHttpRequestHandlerOptions<State extends object> {
dataSerializers?: {
[key: string]: DataSerializerFunction;
};
deserializeQueries?: (
queries: Record<string, string[]>,
schema: Record<string, any>,
) => Record<string, any[]>;
deserializeParams?: (
params: Record<string, string>,
params: Record<string, string | string[]>,
schema: Record<string, any>,
) => Record<string, any>;
}
Expand All @@ -59,7 +54,6 @@ export function createNodeHttpRequestHandler<Context extends object = {}>(
router,
state = {},
prefixUrl,
deserializeQueries = defaultDeserializeQueries,
deserializeParams = defaultDeserializeParams,
} = options;

Expand Down Expand Up @@ -102,18 +96,18 @@ export function createNodeHttpRequestHandler<Context extends object = {}>(
const schema = route._schema;

const headers = joinDuplicateHeaders(req.headers || {});
const params = getPathParams(schema.paths)(pathArray);
const queries = searchParamsToObject(url.search);
const params = {
...getPathParams(schema.paths)(pathArray),
...searchParamsToDredgeParams(url.search),
};

const parsedParams = deserializeParams(params, schema.params);
const parsedQueries = deserializeQueries(queries, schema.queries);

const middlewareRequest: RawRequest = {
url: url.href,
method: req.method || "get",
headers,
params: parsedParams,
queries: parsedQueries,
};

const bodyParser = bodyParsers.get(headers["content-type"] || "");
Expand Down
86 changes: 27 additions & 59 deletions packages/adapters/test/adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,16 +204,26 @@ describe.each(servers)(
router: dredgeRouter([
route
.path("/test/:param")
.params({
a: z.string(),
b: z.string(),
})
.get()
.error((_, d) => {
d.status(500);
})
.use(({ req }, d) => {
d.status(200).json(req.param());
}),
]),

deserializeParams: (params) => {
const newParams: Record<string, any> = {};
const newParams: Record<string, any | any> = {};

Object.entries(params).forEach(([key, value]) => {
if (key === "param") {
if (Array.isArray(value)) {
newParams[key] = value.map((v) => `ds-${v}`);
} else {
newParams[key] = `ds-${value}`;
}
});
Expand All @@ -224,72 +234,26 @@ describe.each(servers)(

expect(
await (
await client("/test/p", {
await client("/test/p?a=apple&b=ball", {
method: "GET",
})
).json(),
).toStrictEqual({
param: "ds-p",
a: "ds-apple",
b: "ds-ball",
});

expect(
await (
await client("/test/pp", {
await client("/test/pp?a=airplane&b=banana", {
method: "GET",
})
).json(),
).toStrictEqual({
param: "ds-pp",
});
});

test("deserializeQueries", async () => {
await startServer({
router: dredgeRouter([
route
.path("/test")
.queries({
a: z.string(),
b: z.string(),
})
.get()
.use(({ req }, d) => {
d.status(200).json({
single: req.query(),
multiple: req.queries(),
});
}),
]),

deserializeQueries: (queries) => {
const newQueries: Record<string, any> = {};
Object.entries(queries).forEach(([key, value]) => {
newQueries[key] = [];

value.forEach((v) => {
newQueries[key].push(`ds-${v}`);
});
});

return newQueries;
},
});

expect(
await (
await client("/test?a=apple&b=ball&b=banana&a=airplane", {
method: "GET",
})
).json(),
).toStrictEqual({
single: {
a: "ds-apple",
b: "ds-ball",
},
multiple: {
a: ["ds-apple", "ds-airplane"],
b: ["ds-ball", "ds-banana"],
},
a: "ds-airplane",
b: "ds-banana",
});
});

Expand Down Expand Up @@ -637,7 +601,7 @@ describe.each(servers)(
router: dredgeRouter([
route
.path("/test")
.queries({
.params({
string: z.string(),
number: z.number(),
boolean: z.boolean(),
Expand All @@ -647,10 +611,14 @@ describe.each(servers)(
.use(({ req }, d) => {
d.status(200).json({
single: {
...req.query(),
date: req.query("date").toISOString().split("T")[0],
...req.param(),
date: req.param("date").toISOString().split("T")[0],
},
multiple: {
number: req.params("number"),
string: req.params("string"),
boolean: req.params("boolean"),
},
multiple: req.queries(),
});
}),
]),
Expand Down Expand Up @@ -684,7 +652,7 @@ describe.each(servers)(
router: dredgeRouter([
route
.path("/test")
.queries({
.params({
string: z.string().optional(),
number: z.number().optional(),
boolean: z.boolean().optional(),
Expand Down
50 changes: 19 additions & 31 deletions packages/common/source/deserialize-params.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,37 @@
import { otherSchemaToDredgeSchema } from "./dredge-schema";

export function deserializeQueries(
queries: Record<string, string[]>,
export function deserializeParams(
params: Record<string, string | string[]>,
schema: Record<string, any>,
) {
const result: Record<string, any[]> = {};
const result: Record<string, any> = {};

for (const [key, value] of Object.entries(queries)) {
for (const [key, value] of Object.entries(params)) {
const sc = schema[key];
if (sc) {
const mySchema = otherSchemaToDredgeSchema(sc);

if (!sc) {
result[key] = value;
continue;
}

const mySchema = otherSchemaToDredgeSchema(sc);

if (Array.isArray(value)) {
if (mySchema?.type === "number") result[key] = value.map(Number);
else if (mySchema?.type === "boolean")
result[key] = value.map((v) => (v === "true" ? true : false));
else if (mySchema?.type === "date")
result[key] = value.map((v) => new Date(v));
else result[key] = value;
} else {
result[key] = value;
}
}

return result;
}

export function deserializeParams(
params: Record<string, string>,
schema: Record<string, any>,
) {
const result: Record<string, any> = {};

for (const [key, value] of Object.entries(params)) {
const sc = schema[key];
if (sc) {
const mySchema = otherSchemaToDredgeSchema(sc);

if (mySchema?.type === "number") result[key] = Number(value);
else if (mySchema?.type === "boolean")
result[key] = value === "true" ? true : false;
else if (mySchema?.type === "date") result[key] = new Date(value);
else result[key] = value;
} else {
result[key] = value;
continue;
}

if (mySchema?.type === "number") result[key] = Number(value);
else if (mySchema?.type === "boolean")
result[key] = value === "true" ? true : false;
else if (mySchema?.type === "date") result[key] = new Date(value);
else result[key] = value;
}

return result;
Expand Down
31 changes: 12 additions & 19 deletions packages/common/source/serialize-params.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,19 @@
export function serializeQueries(queries: Record<string, any[]>) {
const result: Record<string, string[]> = {};
export function serializeParams(params: Record<string, any | any[]>) {
const result: Record<string, string | string[]> = {};

for (const [key, value] of Object.entries(queries)) {
const newValue: any[] = [];
value.forEach((item) => {
if (item instanceof Date) newValue.push(item.toISOString());
else newValue.push(String(item));
});
for (const [key, value] of Object.entries(params)) {
if (Array.isArray(value)) {
const newValue: any[] = [];

result[key] = newValue;
value.forEach((item) => {
if (item instanceof Date) newValue.push(item.toISOString());
else newValue.push(String(item));
});

// if (value instanceof Date) result[key] = value.map((v) => v.toISOString());
// else result[key] = value.map(String);
}
result[key] = newValue;
continue;
}

return result;
}

export function serializeParams(params: Record<string, any>) {
const result: Record<string, string> = {};

for (const [key, value] of Object.entries(params)) {
if (value instanceof Date) result[key] = value.toISOString();
else result[key] = String(value);
}
Expand Down
Loading

0 comments on commit abdcb13

Please sign in to comment.