04-resultManager.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. /**
  2. * 云函数:resultManager(结果库)
  3. * 替代:GET/POST/PUT/DELETE /api/results[/:id]
  4. * actions: list | get | create | update | delete
  5. */
  6. async function handler(request, response) {
  7. try {
  8. await Psql.query(`
  9. CREATE TABLE IF NOT EXISTS "VideoflowResult" (
  10. "objectId" VARCHAR(50) PRIMARY KEY,
  11. "bizId" VARCHAR(255),
  12. "data" JSONB NOT NULL DEFAULT '{}',
  13. "userId" VARCHAR(255) DEFAULT '',
  14. "type" VARCHAR(50) DEFAULT '',
  15. "status" VARCHAR(50) DEFAULT '',
  16. "createdAt" TIMESTAMPTZ DEFAULT NOW(),
  17. "updatedAt" TIMESTAMPTZ DEFAULT NOW()
  18. )
  19. `);
  20. await Psql.query(`CREATE UNIQUE INDEX IF NOT EXISTS idx_videoflow_result_biz ON "VideoflowResult" ("bizId")`);
  21. await Psql.query(`CREATE INDEX IF NOT EXISTS idx_videoflow_result_user ON "VideoflowResult" ("userId")`);
  22. await Psql.query(`CREATE INDEX IF NOT EXISTS idx_videoflow_result_type ON "VideoflowResult" ("type")`);
  23. const action = pickParam(request, 'action') || 'list';
  24. const userId = pickParam(request, 'userId') || '';
  25. if (action === 'list') {
  26. const conds = [], params = [];
  27. if (userId) { params.push(userId); conds.push(`"userId" = $${params.length}`); }
  28. const type = pickParam(request, 'type');
  29. if (type) { params.push(type); conds.push(`"type" = $${params.length}`); }
  30. const status = pickParam(request, 'status');
  31. if (status) { params.push(status); conds.push(`"status" = $${params.length}`); }
  32. const limit = Math.min(parseInt(pickParam(request, 'limit') || '500'), 2000);
  33. const where = conds.length ? `WHERE ${conds.join(' AND ')}` : '';
  34. params.push(limit);
  35. const rows = await Psql.query(
  36. `SELECT * FROM "VideoflowResult" ${where} ORDER BY "createdAt" DESC LIMIT $${params.length}`,
  37. params
  38. );
  39. response.json({ code: 200, success: true, data: rows.map(rowToObj) });
  40. return;
  41. }
  42. if (action === 'get') {
  43. const id = pickParam(request, 'id', 'bizId');
  44. if (!id) return response.json({ code: 400, success: false, error: '缺少 id' });
  45. const rows = userId
  46. ? await Psql.query(`SELECT * FROM "VideoflowResult" WHERE "bizId" = $1 AND "userId" = $2 LIMIT 1`, [id, userId])
  47. : await Psql.query(`SELECT * FROM "VideoflowResult" WHERE "bizId" = $1 LIMIT 1`, [id]);
  48. if (!rows.length) return response.json({ code: 404, success: false, error: '未找到结果' });
  49. response.json({ code: 200, success: true, data: rowToObj(rows[0]) });
  50. return;
  51. }
  52. if (action === 'create') {
  53. const body = pickParam(request, 'result', 'data') || request.body || {};
  54. const bizId = body.id || body.bizId || generateId();
  55. const merged = { ...body, id: bizId, created_at: body.created_at || new Date().toISOString(), updated_at: new Date().toISOString() };
  56. const objectId = generateId();
  57. await Psql.query(
  58. `INSERT INTO "VideoflowResult" ("objectId","bizId","data","userId","type","status")
  59. VALUES ($1,$2,$3,$4,$5,$6)
  60. ON CONFLICT ("bizId") DO UPDATE SET "data"=$3, "type"=$5, "status"=$6, "updatedAt"=NOW()`,
  61. [objectId, bizId, JSON.stringify(merged), userId, merged.type || '', merged.status || '']
  62. );
  63. response.json({ code: 200, success: true, data: merged });
  64. return;
  65. }
  66. if (action === 'update') {
  67. const id = pickParam(request, 'id', 'bizId');
  68. if (!id) return response.json({ code: 400, success: false, error: '缺少 id' });
  69. const patch = pickParam(request, 'result', 'data', 'patch') || request.body || {};
  70. const cur = userId
  71. ? await Psql.query(`SELECT * FROM "VideoflowResult" WHERE "bizId" = $1 AND "userId" = $2 LIMIT 1`, [id, userId])
  72. : await Psql.query(`SELECT * FROM "VideoflowResult" WHERE "bizId" = $1 LIMIT 1`, [id]);
  73. if (!cur.length) return response.json({ code: 404, success: false, error: '未找到结果' });
  74. const merged = { ...rowToObj(cur[0]), ...patch, updated_at: new Date().toISOString() };
  75. await Psql.query(
  76. userId ? `UPDATE "VideoflowResult" SET "data"=$1, "type"=$2, "status"=$3, "updatedAt"=NOW() WHERE "bizId"=$4 AND "userId"=$5` : `UPDATE "VideoflowResult" SET "data"=$1, "type"=$2, "status"=$3, "updatedAt"=NOW() WHERE "bizId"=$4`,
  77. userId ? [JSON.stringify(merged), merged.type || '', merged.status || '', id, userId] : [JSON.stringify(merged), merged.type || '', merged.status || '', id]
  78. );
  79. response.json({ code: 200, success: true, data: merged });
  80. return;
  81. }
  82. if (action === 'delete') {
  83. const id = pickParam(request, 'id', 'bizId');
  84. if (!id) return response.json({ code: 400, success: false, error: '缺少 id' });
  85. const r = userId
  86. ? await Psql.query(`DELETE FROM "VideoflowResult" WHERE "bizId" = $1 AND "userId" = $2 RETURNING "bizId"`, [id, userId])
  87. : await Psql.query(`DELETE FROM "VideoflowResult" WHERE "bizId" = $1 RETURNING "bizId"`, [id]);
  88. response.json({ code: 200, success: true, data: { id, deleted: r.length > 0 } });
  89. return;
  90. }
  91. response.json({ code: 400, success: false, error: `未知 action: ${action}` });
  92. } catch (error) {
  93. console.error('❌ resultManager 失败:', error.message);
  94. response.json({ code: 500, success: false, error: error.message });
  95. }
  96. }
  97. function rowToObj(row) {
  98. const data = typeof row.data === 'string' ? JSON.parse(row.data) : (row.data || {});
  99. return { ...data, objectId: row.objectId, createdAt: row.createdAt, updatedAt: row.updatedAt };
  100. }
  101. function pickParam(request, ...names) {
  102. const sources = [request.params, request.body, request];
  103. for (const src of sources) {
  104. if (!src || typeof src !== 'object') continue;
  105. for (const n of names) {
  106. const v = src[n];
  107. if (v !== undefined && v !== null && v !== '') return v;
  108. }
  109. }
  110. return null;
  111. }
  112. function generateId() {
  113. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  114. let s = '';
  115. for (let i = 0; i < 10; i++) s += chars.charAt(Math.floor(Math.random() * chars.length));
  116. return s;
  117. }