DEV Community

Tom Liang
Tom Liang

Posted on


Simple signup function using FP-TS

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 {
} 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(
        TE.chain(flow(makeUserProfile, UserProfileRepository.insertProfile))

Enter fullscreen mode Exit fullscreen mode

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";"/signup", async (req, res) => {
    const { username, password } = req.body;
    const userE = await signup(username, username, password);
            (e) => res.send({ ok: false, message: e.message }),
            (user) =>
                    ok: true,
                    message: `user ${user.userName} registered `,
Enter fullscreen mode Exit fullscreen mode

There must be better ways to compose the functions, will come back to it when I learn more.

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!