import { AppID } from "@/common/appids"; import { Field } from "@/common/rest-api-client"; import { KintoneRestAPIClient } from "@kintone/rest-api-client"; import { chunk } from "lodash"; const UPDATE_PARAM = { method: "PUT", api: "/k/v1/record.json", } as const; const CREATE_PARAM = { method: "POST", api: "/k/v1/record.json", } as const; type Payload = { app: AppID; id?: string | number; query?: string; record: Field; }; export type BulkRequestResponse = { id?: string; revision?: string }; export type RequestParam = { method: "POST" | "PUT"; api: string; payload: Payload; }; type Callback = (result: BulkRequestResponse) => Promise; export type BulkRequestCallback = Callback; export class BulkRequest { private client: KintoneRestAPIClient; private requests: Array = []; private callbacks: { [index: number]: Callback; } = {}; constructor() { this.client = new KintoneRestAPIClient({ baseUrl: location.origin, }); } update(payload: Payload, callback?: Callback) { const request: RequestParam = { ...UPDATE_PARAM, payload, }; this.requests.push(request); if (callback) { this.callbacks[this.requests.length - 1] = callback; } } create(payload: Payload, callback?: Callback) { const request: RequestParam = { ...CREATE_PARAM, payload, }; this.requests.push(request); if (callback) { this.callbacks[this.requests.length - 1] = callback; } } isSaved() { return this.requests.length === 0; } async save() { this.debug(); let results: BulkRequestResponse[] = []; for (const requests of chunk(this.requests, 20)) { const res = await this.client.bulkRequest({ requests }); results = [...results, ...res.results]; } await this.execCallback(results); this.clear(); return results; } private async execCallback(results: BulkRequestResponse[]) { for (const [index, result] of results.entries()) { if (index in this.callbacks) { console.log("exec callback", this.requests.at(index)); const callback = this.callbacks[index]; await callback(result); } } } clear() { this.requests = []; this.callbacks = []; } debug() { console.log("BulkRequest debug", this, this.requests); } } const bulkRequest = new BulkRequest(); export default bulkRequest;