const handler = async (req: CustomNextApiRequest, res: NextApiResponse<ResponseType>) => {
const body = makeSerializable(req.body);
const method = makeSerializable(req.method);
if (method !== 'POST') {
res.status(405).send('Wrong method');
return;
}
const item = await pipe(
body.itemId,
TE.fromNullable('Item ID is missed'), // TE.TaskEither<string, number>
TE.chain( // pass itemId as 35 to flow
flow(
getItem, // Promise<Item | null>
(item) => () => item, // () => Promise<Item | null>
TE.fromTask, // TE.TaskEither<never, Item | null>
TE.chain(TE.fromNullable('Cant find item')),
)),
)();
const user = await pipe(
getSessionUserId, // () => Promise<number | null>
TE.fromTask, // TE.TaskEither<never, number | null>
TE.chain(
flow( // get number | null
TE.fromNullable('Not logged In'), // TE.TaskEither<string, number>
TE.chain(
flow( // get usereId
getUser, // return Promise<User | null>
(user) => () => user,
TE.fromTask, // TE.TaskEither<never, User | null>
TE.chain(TE.fromNullable('Cant find user')), // TE.TaskEither<string, User>
)),
),
), // TE.TaskEither<string, User>
)();
pipe(
E.Do,
E.bind("_item", () => item),
E.bind("_user", () => user),
E.chain(({ _user, _item }) => isBalanceSufficient(_item, _user)
? E.left('Balance is not sufficient')
: E.right('OK')
),
x => x,
E.fold(
(result) => res.status(400).send(result),
(result) => res.status(200).send(result)
)
);
return;
};
export default handler;