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) { return () => argon2.hash(plainPassword).then(E.right).catch(E.left); } export function signup(userName: string, email: string, password: string) { const makeUserProfile = (userPassword: string) => new UserProfile({ userName, email, userPassword }); return pipe( password, hashPassword, TE.chain(flow(makeUserProfile, UserProfileRepository.insertProfile)) )(); }
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; 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.
Top comments (0)