import { AttributeValue, ElementBatchCreateData, ElementData, FileBatchResponse, Operation, RestApiLink, } from '../../interfaces' import { Api } from '../api' import { CONTENT_TYPES, ENDPOINTS } from '.' interface AttributesBatch { elements: THash[] // Element hashes metadata: TAttr[] // Attribute names } export interface BatchMetadata { elements: { [hash in H]: { element: ElementData; children?: ElementData[] } } } export type BatchCreateResponse = { element: { hash: string links: RestApiLink[] } }[] export class Batch { api: Api constructor(api: Api) { this.api = api } async getBatchAttributes( data: AttributesBatch, ) { const headers = { Accept: CONTENT_TYPES.BATCH_METADATA, 'Content-Type': CONTENT_TYPES.BATCH_METADATA, } return this.api.apisauce.post>( `${ENDPOINTS.BATCH}/metadata?links=false`, data, { headers, }, ) } async createElements(data: ElementBatchCreateData[]) { const headers = { 'Content-Type': CONTENT_TYPES.BATCH_CREATE, } return this.api.apisauce.post( `${ENDPOINTS.BATCH}/elements`, data, { headers, }, ) } async batchFiles(fileBatchData: FilesBatchPostData[]) { const batchDataRequest = await this.api.apisauce.post( `${ENDPOINTS.BATCH}/files`, fileBatchData, { headers: { 'Content-Type': CONTENT_TYPES.BATCH, }, }, ) if (!batchDataRequest.ok) { throw new Error('Cannot update element with batch files') } return batchDataRequest } async batchEditAttributesV2(data: IBatchEditAttributeDataV2[]) { return this.api.apisauce.post( `${ENDPOINTS.MEMBRANE}/batch/attributes`, data, { headers: { 'Content-Type': CONTENT_TYPES.BATCH_EDIT_V2, }, adapter: undefined, }, ) } async batchEditAttributesV1(data: IBatchEditAttributeDataV1[]) { return this.api.apisauce.post( `${ENDPOINTS.MEMBRANE}/batch/attributes`, data, { headers: { 'Content-Type': CONTENT_TYPES.BATCH_EDIT_V1, }, adapter: undefined, }, ) } } export interface FilesBatchPostData { element: { type: string; hash: string } files: FileToSign[] organization: { id: string } } export interface FileToSign { file: { filename: File['name'] file_size: File['size'] md5: string contentType?: string } attribute: { id: string hash?: string } } export interface IBatchEditAttributeDataV1 { organization: { id: string } element: { type: string; hash: string } attributes: { [x: string]: AttributeValue } } export interface SavedElementData { organization: { id: string } operations: Array parent?: { hash: string } } export interface IBatchEditAttributeDataV2 extends SavedElementData { element: { hash: string type: string } }