简化 fp-ts 函数

Simplify fp-ts function

我有这个功能:

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

类型为:

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

这在 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)
  );
};

可以,但是我怎样才能简化最后一个函数呢? 我希望 await getProducts() 在管道中内联,所以我不必预先执行 request 分配。

您可以使用 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一个Task,所以必须在最后调用,才能执行。

如果你真的想避免最后的 (),你可以这样做:

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
);