aboutsummaryrefslogtreecommitdiff
path: root/src/app/api/batch/route.ts
blob: 46e8b3c33b0b6a18b0f5b7b1a7199802536ba597 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { z } from 'zod';
import * as send from '@/app/api/send/route';
import { parseRequest } from '@/lib/request';
import { json, serverError } from '@/lib/response';
import { anyObjectParam } from '@/lib/schema';

const schema = z.array(anyObjectParam);

export async function POST(request: Request) {
  try {
    const { body, error } = await parseRequest(request, schema, { skipAuth: true });

    if (error) {
      return error();
    }

    const errors = [];

    let index = 0;
    let cache = null;
    for (const data of body) {
      // Recreate a fresh Request since `new Request(request)` will have the following error:
      // > Cannot read private member #state from an object whose class did not declare it

      // Copy headers we received, ensure JSON content type, and avoid conflicting content-length
      const headers = new Headers(request.headers);
      headers.set('content-type', 'application/json');
      headers.delete('content-length');

      const newRequest = new Request(request.url, {
        method: 'POST',
        headers,
        body: JSON.stringify(data),
      });

      const response = await send.POST(newRequest);
      const responseJson = await response.json();

      if (!response.ok) {
        errors.push({ index, response: responseJson });
      } else {
        cache ??= responseJson.cache;
      }

      index++;
    }

    return json({
      size: body.length,
      processed: body.length - errors.length,
      errors: errors.length,
      details: errors,
      cache,
    });
  } catch (e) {
    return serverError(e);
  }
}