How to use fp-ts - 10 common examples

To help you get started, we’ve selected a few fp-ts examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github gcanti / io-ts / test / helpers.ts View on Github external
export function assertFailure(codec: t.Any, value: unknown, errors: Array): void {
  const result = codec.decode(value)
  pipe(
    result,
    fold(
      () => {
        assert.deepStrictEqual(PathReporter.report(result), errors)
      },
      /* istanbul ignore next */
      () => {
        throw new Error(`${result} is not a left`)
      }
    )
  )
}
github gcanti / io-ts / test / helpers.ts View on Github external
export function assertStrictEqual(result: t.Validation, expected: any): void {
  pipe(
    result,
    fold(
      /* istanbul ignore next */
      () => {
        throw new Error(`${result} is not a right`)
      },
      a => {
        assert.deepStrictEqual(a, expected)
      }
    )
  )
}
github mikearnaldi / matechs-effect / packages / effect / src / stream / index.ts View on Github external
() =>
                          pipe(
                            T.race(breakerError, waitFiberSlot(fiberSlot)),
                            T.foldExit(
                              c => pushBreaker.cause(c), // if we get a latchError forward it through to downstream
                              constant(pushQueue.offer(none)) // otherwise we are done, so lets forward that
                            )
                          ),
                        next =>
github mikearnaldi / matechs-effect / packages / effect / src / stream / index.ts View on Github external
T.async(res => {
          if (leftover.length > 0) {
            res(Ei.right(O.some(leftover.splice(0, batch))));
          } else {
            if (errors.length > 0) {
              res(Ei.left(errors[0]));
            } else {
              if (open) {
                res(Ei.right(O.some([])));
              } else {
                res(Ei.right(O.none));
              }
            }
          }

          // tslint:disable-next-line: no-empty
          return () => {};
        }),
        every
github mikearnaldi / matechs-effect / packages / effect / src / stream / support.ts View on Github external
op: Ops,
  callback: (r: E.Either>) => void
): () => void {
  switch (op._tag) {
    case "error":
      callback(E.left(op.e));
      // this will never be called
      /* istanbul ignore next */
      // tslint:disable-next-line: no-empty
      return () => {};
    case "complete":
      callback(E.right(O.none));
      // tslint:disable-next-line: no-empty
      return () => {};
    case "offer":
      callback(E.right(O.some(op.a)));
      // tslint:disable-next-line: no-empty
      return () => {};
  }
}
github paritytech / substrate-light-ui / packages / ui-common / src / util / validate.ts View on Github external
// FIXME: check for more methods as necessary
  if (!recipientAddress && extrinsic && extrinsic.method.methodName === 'transfer') {
    errors.recipientAddress = 'Please enter a recipient address.';
  }

  if (currentAccount === recipientAddress) {
    errors.currentAccount = 'You cannot send balance to yourself.';
  }

  if (!amountAsString) {
    errors.amount = 'Please enter an amount';
  }

  return Object.keys(errors).length
    ? left(errors)
    : right({ amountAsString, currentAccount, recipientAddress, extrinsic, ...rest } as Partial & UserInputs);
}
github teamdigitale / io-functions / lib / created_message_queue_handler.ts View on Github external
if (isLeft(errorOrAttachment)) {
    return left(
      TransientError("Cannot store message content")
    );
  }

  // Now that the message content has been stored, we can make the message
  // visible to getMessages by changing the pending flag to false
  const updatedMessageOrError = await lMessageModel.createOrUpdate(
    {
      ...newMessageWithoutContent,
      isPending: false
    },
    createdMessageEvent.message.fiscalCode
  );
  if (isLeft(updatedMessageOrError)) {
    return left(
      TransientError("Cannot update message pending status")
    );
  }

  //
  //  Email notification
  //

  // check if the user has blocked emails sent from this service
  // 'some(true)' in case we must send the notification by email
  // 'none' in case the user has blocked the email channel
  const isEmailBlockedForService = blockedInboxOrChannels.has(
    BlockedInboxOrChannelEnum.EMAIL
  );
github teamdigitale / io-functions / lib / emailnotifications_queue_handler.ts View on Github external
if (isLeft(errorOrActiveMessage)) {
    // if the message is expired no more processing is necessary
    return left(
      ExpiredError(
        `Message expired|notification=${notificationId}|message=${message.id}`
      )
    );
  }

  // fetch the notification
  const errorOrMaybeNotification = await lNotificationModel.find(
    notificationId,
    message.id
  );

  if (isLeft(errorOrMaybeNotification)) {
    const error = errorOrMaybeNotification.value;
    // we got an error while fetching the notification
    return left(
      TransientError(
        `Error while fetching the notification|notification=${notificationId}|message=${
          message.id
        }|error=${error.code}`
      )
    );
  }

  const maybeEmailNotification = errorOrMaybeNotification.value;

  if (isNone(maybeEmailNotification)) {
    // it may happen that the object is not yet visible to this function due to latency
    // as the notification object is retrieved from database (?)
github celo-org / celo-monorepo / packages / contractkit / src / identity / metadata.ts View on Github external
static fromRawString(rawData: string) {
    const data = JSON.parse(rawData)
    // TODO: We should validate:
    // 1. data.claims being an array
    // 2. payload being JSON-parsable
    // This is hard to put into io-ts + we need to eventually do signature checking
    const parsedData = {
      claims: data.claims.map((claim: any) => ({
        payload: JSON.parse(claim.payload),
        signature: claim.signature,
      })),
    }

    const validatedData = IdentityMetadataType.decode(parsedData)

    if (isLeft(validatedData)) {
      // TODO: We could probably return a more useful error in the future
      throw new Error(PathReporter.report(validatedData).join(', '))
    }

    return new IdentityMetadataWrapper(validatedData.right)
  }
github teamdigitale / io-functions / lib / controllers / messages.ts View on Github external
// the user is allowed to see the message when he is either
    // a trusted application or he is the sender of the message
    const isUserAllowed =
      canListMessages ||
      retrievedMessage.senderServiceId === userAttributes.service.serviceId;

    if (!isUserAllowed) {
      // the user is not allowed to see the message
      return ResponseErrorForbiddenNotAuthorized;
    }

    const errorOrMaybeNotification = await notificationModel.findNotificationForMessage(
      retrievedMessage.id
    );

    if (isLeft(errorOrMaybeNotification)) {
      // query failed
      return ResponseErrorQuery(
        "Error while retrieving the notification status",
        errorOrMaybeNotification.value
      );
    }

    const maybeNotification = errorOrMaybeNotification.value;

    const maybeNotificationStatus = maybeNotification.map(n => {
      return {
        email: n.emailNotification ? n.emailNotification.status : undefined
      };
    });

    const maybeContentOrError = await messageModel.getStoredContent(