Middleware that handles requests for HTTP methods registered with the * router. If none of the routes handle a method, then "not allowed" logic * will be used. If a method is supported by some routes, but not the * particular matched router, then "not implemented" will be returned. *
(
options: RouterAllowedMethodsOptions = {},
)
| 773 | * options, of which the value will be returned will be thrown instead of the |
| 774 | * HTTP error. */ |
| 775 | allowedMethods( |
| 776 | options: RouterAllowedMethodsOptions = {}, |
| 777 | ): Middleware { |
| 778 | const implemented = this.#methods; |
| 779 | |
| 780 | const allowedMethods: Middleware = async (context, next) => { |
| 781 | const ctx = context as RouterContext<string>; |
| 782 | await next(); |
| 783 | if (!ctx.response.status || ctx.response.status === Status.NotFound) { |
| 784 | assert(ctx.matched); |
| 785 | const allowed = new Set<HTTPMethods>(); |
| 786 | for (const route of ctx.matched) { |
| 787 | for (const method of route.methods) { |
| 788 | allowed.add(method); |
| 789 | } |
| 790 | } |
| 791 | |
| 792 | const allowedStr = [...allowed].join(", "); |
| 793 | if (!implemented.includes(ctx.request.method)) { |
| 794 | if (options.throw) { |
| 795 | throw options.notImplemented |
| 796 | ? options.notImplemented() |
| 797 | : new errors.NotImplemented(); |
| 798 | } else { |
| 799 | ctx.response.status = Status.NotImplemented; |
| 800 | ctx.response.headers.set("Allow", allowedStr); |
| 801 | } |
| 802 | } else if (allowed.size) { |
| 803 | if (ctx.request.method === "OPTIONS") { |
| 804 | ctx.response.status = Status.OK; |
| 805 | ctx.response.headers.set("Allow", allowedStr); |
| 806 | } else if (!allowed.has(ctx.request.method)) { |
| 807 | if (options.throw) { |
| 808 | throw options.methodNotAllowed |
| 809 | ? options.methodNotAllowed() |
| 810 | : new errors.MethodNotAllowed(); |
| 811 | } else { |
| 812 | ctx.response.status = Status.MethodNotAllowed; |
| 813 | ctx.response.headers.set("Allow", allowedStr); |
| 814 | } |
| 815 | } |
| 816 | } |
| 817 | } |
| 818 | }; |
| 819 | |
| 820 | return allowedMethods; |
| 821 | } |
| 822 | |
| 823 | /** Register named middleware for the specified routes when the `DELETE`, |
| 824 | * method is requested. */ |