1.0.1 • Published 5 years ago
servant-ts v1.0.1
Servant TS
A Haskell's Servant inspired library for defining type-safe REST APIs using Typescript.
Right now, it only supports express but it can support other server setups.
Inspiration and similar projects
Obviously Servant, but also Rest.ts and RESTyped.
Installation
npm i -S servant-ts fp-ts io-ts
How to use it
First, you need to define your API, optionally using the awesome library io-ts.
import * as t from "io-ts";
import { GET, capture, asJson } from "servant-ts/dist/io-ts";
const User = t.strict({
id: t.Int,
username: t.string,
email: t.string
});
/*
* GET /user/:id
* where :id must be an integer
*
* Response example:
* Status: 200
* Contet-Type: application/json
* Body:
* {
* "id": 1,
* "username": "johndoe",
* "email": "johndoe@email.com"
* }
*/
const api = {
userById: GET`/user/${capture("id", t.Int)}`
.response(asJson(User))
};
Then, you need to implement tha API:
const app = express();
app.use(
"/api",
createApi(api, {
userById: async (request) => {
const { captures: { id } } = request;
// get the user, maybe from a database ...
return user;
}
})
);
Example
A backend implementation of the Real World specification using this library and Postgres SQL.
Future work
- Make it solid
- Better error handling and specification
- Swagger specification generator
- Fastify support
- JSON schema generator
- Make io-ts optional