/** * Copyright 2022 Gravwell, Inc. All rights reserved. * * Contact: [legal@gravwell.io](mailto:legal@gravwell.io) * * This software may be modified and distributed under the terms of the MIT * license. See the LICENSE file for details. */ import * as FormData from 'form-data'; import { FileMetadata } from '~/models/file/file-metadata'; import { RawBaseFileMetadata } from '~/models/file/raw-file-metadata'; import { toRawUpdatableFile } from '~/models/file/to-raw-updatable-file'; import { UpdatableFile } from '~/models/file/updatable-file'; import { APIContext } from '../utils/api-context'; import { buildHTTPRequestWithAuthFromContext } from '../utils/build-http-request'; import { buildURL } from '../utils/build-url'; import { HTTPRequestOptions } from '../utils/http-request-options'; import { parseJSONResponse } from '../utils/parse-json-response'; import { makeGetOneFileDetails } from './get-one-file-details'; export const makeUpdateOneFile = (context: APIContext): ((data: UpdatableFile) => Promise) => { const getOneFile = makeGetOneFileDetails(context); return async (data: UpdatableFile): Promise => { const templatePath = '/api/files/{fileID}?admin=true'; const url = buildURL(templatePath, { ...context, protocol: 'http', pathParams: { fileID: data.id } }); try { const current = await getOneFile(data.id); const updatedKeys = new Set(Object.keys(data)) as Set; const fileUpdate = async (): Promise => { const targetedKeys: Array> = ['file']; const hasTargetedKey = targetedKeys.some(key => updatedKeys.has(key)); if (!hasTargetedKey) { return Promise.resolve(); } const formData = new FormData(); formData.append('file', data.file); const baseRequestOptions: HTTPRequestOptions = { body: formData as any, }; const req = buildHTTPRequestWithAuthFromContext(context, baseRequestOptions); const raw = await context.fetch(url, { ...req, method: 'PUT' }); await parseJSONResponse(raw); }; const metadataUpdate = async (): Promise => { const targetedKeys: Array> = [ 'name', 'description', 'userID', 'labels', 'globalID', 'groupIDs', 'isGlobal', ]; const hasTargetedKey = targetedKeys.some(key => updatedKeys.has(key)); if (!hasTargetedKey) { return Promise.resolve(); } const baseRequestOptions: HTTPRequestOptions = { body: JSON.stringify(toRawUpdatableFile(data, current)), headers: { 'Content-Type': 'application/json' }, }; const req = buildHTTPRequestWithAuthFromContext(context, baseRequestOptions); const raw = await context.fetch(url, { ...req, method: 'PATCH' }); await parseJSONResponse(raw); }; await metadataUpdate(); await fileUpdate(); return getOneFile(data.id); } catch (err) { if (err instanceof Error) { throw err; } throw Error('Unknown error'); } }; };