Skip to content

Build a check routine ​

In a project, you’ll often want to run a series of checks in several places.

The clearest example is authentication. You first retrieve a token, then decrypt it, and finally verify that the user exists.

That’s why @duplojs/http introduces the ✨process✨.

ts
import { ResponseContract, 
useProcessBuilder
} from "@duplojs/http";
import {
DPE
,
E
,
O
,
pipe
} from "@duplojs/utils";
import {
checkToken
} from "./checkToken";
import {
userExist
} from "./checker";
export const
authenticationProcess
=
useProcessBuilder
()
.
extract
({
headers
: {
authorization
:
DPE
.
string
(),
}, }) .
cut
(
ResponseContract.
unauthorized
("token.invalid"),
({
authorization
}, {
response
,
output
}) =>
pipe
(
authorization
,
checkToken
,
E
.
whenIsRight
(
({
userId
}) =>
output
({
authenticatedUserId
:
userId
}),
),
E
.
whenIsLeft
(() =>
response
("token.invalid")),
), ) .
check
(
userExist
,
{
input
:
O
.
getProperty
("authenticatedUserId"),
result
: "user.find",
otherwise
: ResponseContract.
notFound
("token.user.notfound"),
indexing
: "user",
}, ) .
exports
(["user"]);

The exports method ends the creation of a process and exposes its values to the routes or processes that will implement it.

INFO

The code above uses functions from @duplojs/utils. If some parts seem unclear, check the documentation.

Implementing a process in a route ​

ts
import { ResponseContract, 
useRouteBuilder
} from "@duplojs/http";
import {
authenticationProcess
} from "./process";
import {
userSchema
} from "./schema";
useRouteBuilder
("GET", "/some-action")
.
exec
(
authenticationProcess
, {
imports
: ["user"] })
.
handler
(
ResponseContract.
ok
("some-information.send",
userSchema
),
({
user
}, {
response
}) =>
response
("some-information.send",
user
),
);

To implement a process in a route, simply call the builder’s exec method. You can configure the implementation by selecting, for example, the variables you want to import from the process into your route.

Go faster ​

You can create your own builder with pre-implemented process steps as a preflight.

ts
import { 
usePreflightBuilder
} from "@duplojs/http";
import {
authenticationProcess
} from "./process";
export const
useAuthenticatedRouteBuilder
=
usePreflightBuilder
()
.
exec
(
authenticationProcess
, {
imports
: ["user"] })
.
useRouteBuilder
;

All that’s left is to create your routes with...

ts
import { ResponseContract } from "@duplojs/http";
import { 
useAuthenticatedRouteBuilder
} from "./authenticatedRouteBuilder";
import {
userSchema
} from "./schema";
useAuthenticatedRouteBuilder
("GET", "/some-action")
.
handler
(
ResponseContract.
ok
("some-information.send",
userSchema
),
({
user
}, {
response
}) =>
response
("some-information.send",
user
),
);

Released under the MIT License.