diff --git a/index.d.ts b/index.d.ts index 6d0e1aa3..81df9958 100644 --- a/index.d.ts +++ b/index.d.ts @@ -57,17 +57,17 @@ declare namespace Router { store: any ) => void; - interface ConstraintStrategy { + interface ConstraintStrategy { name: string, mustMatchWhenDerived?: boolean, storage() : { - get(version: String) : Handler | null, - set(version: String, store: Handler) : void, - del(version: String) : void, + get(value: T) : Handler | null, + set(value: T, handler: Handler) : void, + del(value: T) : void, empty() : void }, validate(value: unknown): void, - deriveConstraint(req: Req, ctx?: Context) : String, + deriveConstraint(req: Req, ctx?: Context) : T, } interface Config { diff --git a/test/types/router.test-d.ts b/test/types/router.test-d.ts index e36ee58e..0c1f79f8 100644 --- a/test/types/router.test-d.ts +++ b/test/types/router.test-d.ts @@ -111,3 +111,61 @@ let http2Res!: Http2ServerResponse; expectType(router.prettyPrint()) } + +// Custom Constraint +{ + let handler: Router.Handler + + interface AcceptAndContentType { accept?: string, contentType?: string } + + const customConstraintWithObject: Router.ConstraintStrategy = { + name: "customConstraintWithObject", + deriveConstraint(req: Router.Req, ctx: Context | undefined): AcceptAndContentType { + return { + accept: req.headers.accept, + contentType: req.headers["content-type"] + } + }, + validate(value: unknown): void {}, + storage () { + return { + get (version) { return handler }, + set (version, handler) {}, + del (version) {}, + empty () {} + } + } + } + const storageWithObject = customConstraintWithObject.storage() + const acceptAndContentType: AcceptAndContentType = { accept: 'application/json', contentType: 'application/xml' } + + expectType(customConstraintWithObject.deriveConstraint(http1Req, http1Res)) + expectType(storageWithObject.empty()) + expectType(storageWithObject.del(acceptAndContentType)); + expectType | null>(storageWithObject.get(acceptAndContentType)); + expectType(storageWithObject.set(acceptAndContentType, () => {})); + + const customConstraintWithDefault: Router.ConstraintStrategy = { + name: "customConstraintWithObject", + deriveConstraint(req: Router.Req, ctx: Context | undefined): string { + return req.headers.accept ?? '' + }, + validate(value: unknown): void {}, + storage () { + return { + get (version) { return handler }, + set (version, handler) {}, + del (version) {}, + empty () {} + } + } + } + + const storageWithDefault = customConstraintWithDefault.storage() + + expectType(customConstraintWithDefault.deriveConstraint(http1Req, http1Res)) + expectType(storageWithDefault.empty()) + expectType(storageWithDefault.del('')); + expectType | null>(storageWithDefault.get('')); + expectType(storageWithDefault.set('', () => {})); +}