Skip to content

Commit

Permalink
fix: add missing optional parameter type inference
Browse files Browse the repository at this point in the history
  • Loading branch information
mooyoul committed Sep 25, 2020
1 parent 9ddcd07 commit 96714b5
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 8 deletions.
2 changes: 2 additions & 0 deletions src/__test__/e2e/complex_api_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ describe("Calling complex API", () => {
children: [
Route.POST("", { operationId: "follow" }, {
testId: Parameter.Query(Type.Number()),
optional: Parameter.Query(Type.Optional(Type.String())),
update: Parameter.Body(Type.Object({
fieldA: Type.Number(),
})),
Expand All @@ -44,6 +45,7 @@ describe("Calling complex API", () => {

return this.json({
testId,
optional: this.params.optional,
userId,
update: this.params.update,
});
Expand Down
6 changes: 1 addition & 5 deletions src/__test__/routing-context_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,11 +206,7 @@ describe("RoutingContext", () => {
),
});

expect(context.params).to.deep.eq({
// update: {
// complex: null,
// },
});
expect(context.params).to.deep.eq({});
});
});
});
Expand Down
18 changes: 15 additions & 3 deletions src/routing-context.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Static, TStatic, Type } from "@serverless-seoul/typebox";
import { Static, TOptional, TStatic, Type } from "@serverless-seoul/typebox";
import * as Ajv from "ajv";
import * as _ from "lodash";
import * as qs from "qs";
Expand All @@ -15,6 +15,14 @@ const ajv = new Ajv({
removeAdditional: "all",
});

type NamespaceParameterType<T extends { [P in keyof T]: TStatic }> = string extends keyof T
? {}
: { [P in keyof T]: Static<T[P]> };

type RouteParameterType<T extends { [P in keyof T]: ParameterDefinition<any> }> = string extends keyof T
? {}
: { [P in keyof T]: T[P] extends TOptional<any> ? Static<T[P]["def"]> : Static<T[P]> };

// ---- RoutingContext
export class RoutingContext<
T extends { [P in keyof T]: ParameterDefinition<any> },
Expand Down Expand Up @@ -56,8 +64,12 @@ export class RoutingContext<
}
}
private readonly validatedParams:
(string extends keyof U ? {} : { [P in keyof U]: Static<U[P]> }) &
(string extends keyof T ? {} : { [P in keyof T]: Static<T[P]["def"]> }) &
// Inferred Namespace Parameter
NamespaceParameterType<U> &
// Inferred Route Parameter
RouteParameterType<T> &
// Unknown keys should be unknown type
// Below type is just for assigning custom parameter in Namespace#before
{ [key: string]: unknown };
private normalizedHeaders: { [key: string]: string } | null;

Expand Down

0 comments on commit 96714b5

Please sign in to comment.