This content originally appeared on DEV Community and was authored by Tom Liang
I tried to make a simple user signup function using FP-TS.
// user-controller.ts
import argon2 from "argon2";
import * as E from "fp-ts/Either";
import { flow, pipe } from "fp-ts/lib/function";
import * as TE from "fp-ts/TaskEither";
import {
UserProfile,
UserProfileRepository,
} from "../db/entities/user_profile";
function hashPassword(plainPassword: string): TE.TaskEither<Error, string> {
return () =>
argon2
.hash(plainPassword)
.then((hashed) => E.right(hashed))
.catch((e) => E.left(e));
}
export function signup(
userName: string,
email: string,
password: string
): TE.TaskEither<Error, UserProfile> {
const makeUserProfile = (hashed: string) => {
return new UserProfile({ userName, email, userPassword: hashed });
};
//the reason to "chain" is because the nested TaskEithers need to be flattened
const program = flow(
hashPassword,
TE.chain(flow(makeUserProfile, UserProfileRepository.insertProfile))
);
return pipe(password, program);
}
How to call:
// user-router.ts
import express from "express";
import { pipe } from "fp-ts/lib/function";
import { signup } from "../controllers/user-controller";
import * as E from "fp-ts/lib/Either";
router.post("/signup", async (req, res) => {
const { username, password } = req.body;
// we have to call the asynchronous Task
const userE = await signup(username, username, password)();
pipe(
userE,
E.bimap(
(e) => res.send({ ok: false, message: e.message }),
(user) =>
res.send({
ok: true,
message: `user ${user.userName} registered `,
})
)
);
});
There must be better ways to compose the functions, will come back to it when I learn more.
This content originally appeared on DEV Community and was authored by Tom Liang

Tom Liang | Sciencx (2021-12-29T01:53:00+00:00) Simple signup function using FP-TS. Retrieved from https://www.scien.cx/2021/12/29/simple-signup-function-using-fp-ts/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.