Create your first route
ts
import { ResponseContract, useRouteBuilder } from "@duplojs/http";
import { DPE } from "@duplojs/utils";
import { userSchema } from "./schema";
import { getUsers } from "./getUsers";
useRouteBuilder("GET", "/users")
.extract({
query: {
page: DPE.int().min(0),
quantityPerPage: DPE.int().min(5).max(20),
},
})
.handler(
ResponseContract.ok("users.findMany", userSchema.array()),
async({ page, quantityPerPage }, { response }) => {
const manyUser = await getUsers({
page,
quantityPerPage,
});
return response("users.findMany", manyUser);
},
);Just import the useRouteBuilder function from @duplojs/http to start creating a route. Each method called on this builder adds a step to the route. The execution order of these steps is sequential. A route is read from top to bottom.
The handler method completes the route creation. This method automatically adds the route to the routeStore.
WARNING
Don’t forget to import the files containing your routes; otherwise they won’t be executed and the routes won’t be available in the routeStore.
ts
import { createHub, routeStore } from "@duplojs/http";
import "./route"; // don't forget !
const hub = createHub({ environment: "DEV" })
.register(routeStore.getAll());What is a ResponseContract?
ResponseContracts let you explicitly define the possible responses of a step. THEY ARE REQUIRED! The body structure is defined via a dataParser from @duplojs/utils.
They allow you to:
- associate an information value with a body structure and an HTTP status.
- clearly see what the route returns and avoid sending extra fields (hello password in the frontend 👋).
- assist during tests to ensure the structures you return are correct.
- be interpreted at runtime to generate Swagger or type contracts for HTTP clients.
ts
import { ResponseContract } from "@duplojs/http";
import { DPE } from "@duplojs/utils";
ResponseContract.ok("superResponse", DPE.string());
ResponseContract.created("superResponse", DPE.object({
username: DPE.string(),
age: DPE.number(),
}));
ResponseContract.noContent("superResponse");
ResponseContract.conflict("email.alreadyUse");
ResponseContract.notFound("user.notfound");
ResponseContract.notFound("product.notfound");