简体   繁体   English

简化 fp-ts 函数

[英]Simplify fp-ts function

I have this function:我有这个功能:

export const getProducts = makeRequest(
  /** Your query */
  `asasd*[_type == "product"] {
      _id,
      title
    }`,
  /** Optionally transform the response */
  (i) => i,
  /** Validate exact type */
  D.array(Product)
);

which is of type:这是类型:

const getProducts: TaskEither<Error, {
    _id: string;
    title: string;
}[]>

This is used in a Next.js API route like this:这在 Next.js API 路由中使用,如下所示:

export default async (
  _: NextApiRequest,
  res: NextApiResponse<Array<Product>>
) => {
  const request = await getProducts();
  return pipe(
    request,
    E.fold((v) => res.status(400).end(v.message), res.status(200).json)
  );
};

It work, but how can I simplify the last function?它工作,但我怎样才能简化最后一个功能? I would like for await getProducts() to be inline in the pipe, so I don't have to do the request assignment up front.我希望await getProducts()在管道中内联,所以我不必预先进行request分配。

You can use map from the Task module:您可以使用Task模块中的map

import * as T from 'fp-ts/Task'

export default async (
  _: NextApiRequest,
  res: NextApiResponse<Array<Product>>;
) => pipe(
  request,
  T.map(E.fold((v) => res.status(400).end(v.message), res.status(200).json))
)();

pipe(request, T.map(...))) returns a Task , so you must call it at the end so that it is executed. pipe(request, T.map(...)))返回一个Task ,因此您必须在最后调用它才能执行它。

If you really wanted to avoid the () at the end, you could do something like this:如果你真的想避免最后的() ,你可以这样做:

const runTask = async <A>(task: T.Task<A>): Promise<A> => task();

export default async (
  _: NextApiRequest,
  res: NextApiResponse<Array<Product>>;
) => pipe(
  request,
  T.map(E.fold((v) => res.status(400).end(v.message), res.status(200).json)),
  runTask
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM