/** * 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 { isString } from 'lodash'; import { RawResource } from '~/models/resource/raw-resource'; import { Resource } from '~/models/resource/resource'; import { toResource } from '~/models/resource/to-resource'; import { UUID } from '~/value-objects/id'; import { APIContext } from '../utils/api-context'; import { buildHTTPRequestWithAuthFromContext } from '../utils/build-http-request'; import { buildURL } from '../utils/build-url'; import { File } from '../utils/file'; import { HTTPRequestOptions } from '../utils/http-request-options'; import { parseJSONResponse } from '../utils/parse-json-response'; export const makeSetOneResourceContent = (context: APIContext) => async (resourceID: UUID, file: File): Promise => { const resourcePath = '/api/resources/{resourceID}/raw'; const url = buildURL(resourcePath, { ...context, protocol: 'http', pathParams: { resourceID } }); try { const baseRequestOptions: HTTPRequestOptions = { body: toFormData(file) as any, }; const req = buildHTTPRequestWithAuthFromContext(context, baseRequestOptions); const raw = await context.fetch(url, { ...req, method: 'PUT' }); const rawRes = await parseJSONResponse(raw); return toResource(rawRes); } catch (err) { if (err instanceof Error) { throw err; } throw Error('Unknown error'); } }; const toFormData = (file: File): FormData => { const formData = new FormData(); formData.append('file', ...parseFile(file)); return formData; }; const parseFile = (file: File): [any, FormData.AppendOptions?] => isString(file) ? [file, { filename: 'whatever.txt' }] : [file];