How to use the fp-ts/lib/Either.fold function in fp-ts

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 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 elastic / kibana / x-pack / legacy / plugins / infra / server / routes / log_analysis / validation / indices.ts View on Github external
async (requestContext, request, response) => {
      try {
        const payload = pipe(
          validationIndicesRequestPayloadRT.decode(request.body),
          fold(throwErrors(Boom.badRequest), identity)
        );

        const { fields, indices } = payload.data;
        const errors: ValidationIndicesError[] = [];

        // Query each pattern individually, to map correctly the errors
        await Promise.all(
          indices.map(async index => {
            const fieldCaps = await framework.callWithRequest(requestContext, 'fieldCaps', {
              allow_no_indices: true,
              fields: fields.map(field => field.name),
              ignore_unavailable: true,
              index,
            });

            if (fieldCaps.indices.length === 0) {
github stoplightio / prism / packages / core / src / __tests__ / utils.ts View on Github external
export function assertLeft(e: E.Either, onLeft: (a: L) => void = noop): asserts e is E.Left {
  pipe(
    e,
    E.fold(onLeft, a => {
      throw new Error('Left expected, got a Right: ' + a);
    })
  );
}
github elastic / kibana / x-pack / legacy / plugins / infra / server / lib / sources / sources.ts View on Github external
private async getStaticDefaultSourceConfiguration() {
    const staticConfiguration = await this.libs.configuration.get();
    const staticSourceConfiguration = pipe(
      runtimeTypes
        .type({
          sources: runtimeTypes.type({
            default: StaticSourceConfigurationRuntimeType,
          }),
        })
        .decode(staticConfiguration),
      map(({ sources: { default: defaultConfiguration } }) => defaultConfiguration),
      fold(constant({}), identity)
    );

    return mergeSourceConfiguration(defaultSourceConfiguration, staticSourceConfiguration);
  }
github stoplightio / prism / packages / core / src / factory.ts View on Github external
const inputValidation = (
    resource: Resource,
    input: Input,
    config: Config
  ): TE.TaskEither =>
    pipe(
      sequenceValidation(
        config.validateRequest ? components.validateInput({ resource, element: input }) : E.right(input),
        config.checkSecurity ? components.validateSecurity({ resource, element: input }) : E.right(input)
      ),
      E.fold(
        validations => validations as IPrismDiagnostic[],
        () => []
      ),
      validations => TE.right({ resource, validations })
    );
github elastic / kibana / x-pack / legacy / plugins / infra / public / containers / logs / log_analysis / api / ml_get_jobs_summary_api.ts View on Github external
spaceId: string,
  sourceId: string,
  jobTypes: JobType[]
) => {
  const response = await kfetch({
    method: 'POST',
    pathname: '/api/ml/jobs/jobs_summary',
    body: JSON.stringify(
      fetchJobStatusRequestPayloadRT.encode({
        jobIds: jobTypes.map(jobType => getJobId(spaceId, sourceId, jobType)),
      })
    ),
  });
  return pipe(
    fetchJobStatusResponsePayloadRT.decode(response),
    fold(throwErrors(createPlainError), identity)
  );
};
github gcanti / elm-ts / examples / Http.tsx View on Github external
return dispatch => (
    <div>
      <h2>{model.topic}</h2>
      {pipe(
        model.gifUrl,
        O.fold(
          () =&gt; <span>loading...</span>,
          E.fold(error =&gt; <span>Error: {error._tag}</span>, gifUrl =&gt; <img src="{gifUrl}">)
        )
      )}
      <button> dispatch({ type: 'MorePlease' })}&gt;New Gif</button>
    </div>
  )
}
github elastic / kibana / x-pack / legacy / plugins / siem / server / lib / pinned_event / saved_object.ts View on Github external
const convertSavedObjectToSavedPinnedEvent = (
  savedObject: unknown,
  timelineVersion?: string | undefined | null
): PinnedEventSavedObject =>
  pipe(
    PinnedEventSavedObjectRuntimeType.decode(savedObject),
    map(savedPinnedEvent => ({
      pinnedEventId: savedPinnedEvent.id,
      version: savedPinnedEvent.version,
      timelineVersion,
      ...savedPinnedEvent.attributes,
    })),
    fold(errors => {
      throw new Error(failure(errors).join('\n'));
    }, identity)
  );
github DenisFrezzato / hyper-ts-fastify / src / index.ts View on Github external
H.execMiddleware(middleware, new FastifyConnection<i>(req, res))().then(e =&gt;
    pipe(
      e,
      fold(constVoid, c =&gt; {
        const { actions: list, reply } = c as FastifyConnection
        const len = list.length
        const actions = LL.toReversedArray(list)
        for (let i = 0; i &lt; len; i++) {
          run(reply, actions[i])
        }
      }),
    ),
  )</i>
github elastic / kibana / x-pack / legacy / plugins / infra / server / graphql / metrics / resolvers.ts View on Github external
async metrics(source, args, { req }) {
      const sourceConfiguration = pipe(
        SourceConfigurationRuntimeType.decode(source.configuration),
        fold(errors => {
          throw new Error(failure(errors).join('\n'));
        }, identity)
      );

      UsageCollector.countNode(args.nodeType);
      const options = {
        nodeIds: args.nodeIds,
        nodeType: args.nodeType,
        timerange: args.timerange,
        metrics: args.metrics,
        sourceConfiguration,
      };
      return libs.metrics.getMetrics(req, options);
    },
  },