Route Requests Through a Handler per Method
Write the code, see it run, pass the checks.
The problem
- medium
- Code
- Pro
Export a Method type (GET, POST, PUT or DELETE), a Req type ({ path, body? }, both strings), a Res type ({ status, body }, a number and a string) and a Routes type with a handler for every method. Write createRouter(routes), which returns dispatch(method, req): it calls that method's handler with the request and returns its response, and answers { status: 405, body: Method not allowed } for any other method arriving at runtime. Type Routes so a missing method is a type error and each handler gets a typed request, and type dispatch so an unknown method is a type error.
Your code must pass
- Calls the handler for the method
- Passes the request through
- Answers 405 for any other method
- Has no type errors
- A missing method is a type error
- Handlers get a typed request
- Rejects an unknown method