0

我想忽略使用 fp-ts 的某些错误(如果它们发生,则表示一切顺利,即在注册过程中缺少帐户)。

我有以下代码:

export const handleSignup = async (server: FastifyInstance): Promise<void> => {
  server.post('/signup', async (req, res) => {
    const {email} = req.body as SignupPostData
    const {redirectUri} = req.query as Record<'redirectUri', string>

    return pipe(
      withDb(lookupAccountByEmail)(email),
      TE.chain(() => flow(generateMagicLinkToken, TE.fromEither)(email)),
      TE.chain(sendSignupEmail(email, redirectUri))
    )().then(foldReply<SignupApiResponse>(res))
  })
}

lookupAccountByEmail函数将返回一个帐户,或者将返回一个错误对象。如果返回一个帐户,我需要返回一个带有代码“帐户存在”的错误。如果返回代码为“account-not-found”的错误对象,我希望一切都继续进行,就好像没有问题一样。如果返回带有任何其他代码的错误对象,它应该仍然是错误的。

在 fp-ts 中处理这个问题的最佳方法是什么?

4

1 回答 1

1

您可以使用 TE.fold。

const doSignup = pipe(
  generateMagicLinkToken(email),
  TE.fromEither,
  TE.chain(sendSignupEmail(email, redirectUri))
)
return pipe(
  email,
  withDb(lookupAccountByEmail),
  TE.fold(
    left => left.error === 'account-not-found' ? doSignup : TE.left(left)
    right => TE.left({error: 'account-exits'})
  ),
  T.map(foldReply<SignupApiResponse>(res))
)()
于 2020-08-28T23:42:17.613 回答