progress.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import type { NextApiRequest, NextApiResponse } from "next";
  2. import { build, EventBus } from "@luckysheet/cli";
  3. import type { IObj, IEventBus } from "@luckysheet/cli";
  4. import { Low, JSONFile } from "lowdb";
  5. type IData = {
  6. msg: string;
  7. };
  8. type IDBData = {
  9. buildObj: {
  10. [key: string]: string[];
  11. };
  12. };
  13. const adapter = new JSONFile<IDBData>("./db.json");
  14. const db = new Low(adapter);
  15. export default async function handler(
  16. req: NextApiRequest,
  17. res: NextApiResponse<IData>
  18. ) {
  19. res.writeHead(200, {
  20. "Content-Type": "text/event-stream;charset=utf-8",
  21. "Cache-Control": "no-cache,no-transform",
  22. Connection: "keep-alive",
  23. "Access-Control-Allow-Origin": "*",
  24. });
  25. // res.write("retry: 100000\n");
  26. const queryObject = req.query;
  27. console.log(queryObject);
  28. // Subscribe to event
  29. const eventBus: IEventBus = new EventBus();
  30. let id = 0;
  31. eventBus.subscribe("progress", (obj: IObj, num: number) => {
  32. res.write("event: progress\n");
  33. res.write("id: " + ++id + "\n");
  34. res.write("data: " + obj.msg + "-" + num + "\n\n");
  35. });
  36. await db.read();
  37. db.data = db.data || { buildObj: {} };
  38. const { buildObj } = db.data;
  39. const buildList = buildObj[queryObject.buildId as string];
  40. // Though in some cases TypeScript can infer them
  41. // const buildList = await db.get(queryObject.buildId);
  42. build(
  43. {
  44. include: buildList,
  45. },
  46. {
  47. eventBus,
  48. buildId: queryObject.buildId as string,
  49. }
  50. )
  51. .then((e: any) => {
  52. res.write("event: progress\n");
  53. res.write("id: " + ++id + "\n");
  54. res.write("data: " + "Success" + "-" + 1 + "\n\n");
  55. // res.write("event: message\n");
  56. // res.write("id: " + ++id + "\n");
  57. // res.write("data: Success\n\n");
  58. res.end();
  59. })
  60. .catch((e: any) => {
  61. res.write("event: progress\n");
  62. res.write("id: " + ++id + "\n");
  63. res.write("data: " + "Fail" + "-" + 0 + "\n\n");
  64. // res.write("event: message\n");
  65. // res.write("id: " + ++id + "\n");
  66. // res.write("data: Fail\n\n");
  67. res.end();
  68. });
  69. }