/* * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. */ import * as utils from "../internal/utils"; import * as errors from "../sdk/models/errors"; import * as operations from "../sdk/models/operations"; import * as shared from "../sdk/models/shared"; import { SDKConfiguration } from "./sdk"; import { AxiosInstance, AxiosRequestConfig, AxiosResponse, RawAxiosRequestHeaders } from "axios"; export class Uploads { private sdkConfiguration: SDKConfiguration; constructor(sdkConfig: SDKConfiguration) { this.sdkConfiguration = sdkConfig; } /** * Abort multipart upload * * @remarks * This endpoint aborts the multipart upload initiated with /create-multipart. * This should be used when cancelling the upload. It does not matter if parts * were already uploaded into the external storage provider. * * You must have the correct permissions and CORS settings configured in your * external provider. We support AWS S3 as the default. See: * * https://meta.discourse.org/t/-/210469#s3-multipart-direct-uploads-4. * * An external file store must be set up and `enable_direct_s3_uploads` must * be set to true for this endpoint to function. * * */ async abortMultipart( req: operations.AbortMultipartRequestBody, config?: AxiosRequestConfig ): Promise { if (!(req instanceof utils.SpeakeasyBase)) { req = new operations.AbortMultipartRequestBody(req); } const baseURL: string = utils.templateUrl( this.sdkConfiguration.serverURL, this.sdkConfiguration.serverDefaults ); const operationUrl: string = baseURL.replace(/\/$/, "") + "/uploads/abort-multipart.json"; let [reqBodyHeaders, reqBody]: [object, any] = [{}, null]; try { [reqBodyHeaders, reqBody] = utils.serializeRequestBody(req, "request", "json"); } catch (e: unknown) { if (e instanceof Error) { throw new Error(`Error serializing request body, cause: ${e.message}`); } } const client: AxiosInstance = this.sdkConfiguration.defaultClient; let globalSecurity = this.sdkConfiguration.security; if (typeof globalSecurity === "function") { globalSecurity = await globalSecurity(); } if (!(globalSecurity instanceof utils.SpeakeasyBase)) { globalSecurity = new shared.Security(globalSecurity); } const properties = utils.parseSecurityProperties(globalSecurity); const headers: RawAxiosRequestHeaders = { ...reqBodyHeaders, ...config?.headers, ...properties.headers, }; headers["Accept"] = "application/json"; headers["user-agent"] = this.sdkConfiguration.userAgent; const httpRes: AxiosResponse = await client.request({ validateStatus: () => true, url: operationUrl, method: "post", headers: headers, responseType: "arraybuffer", data: reqBody, ...config, }); const responseContentType: string = httpRes?.headers?.["content-type"] ?? ""; if (httpRes?.status == null) { throw new Error(`status code not found in response: ${httpRes}`); } const res: operations.AbortMultipartResponse = new operations.AbortMultipartResponse({ statusCode: httpRes.status, contentType: responseContentType, rawResponse: httpRes, }); const decodedRes = new TextDecoder().decode(httpRes?.data); switch (true) { case httpRes?.status == 200: if (utils.matchContentType(responseContentType, `application/json`)) { res.object = utils.objectToClass( JSON.parse(decodedRes), operations.AbortMultipartResponseBody ); } else { throw new errors.SDKError( "unknown content-type received: " + responseContentType, httpRes.status, decodedRes, httpRes ); } break; } return res; } /** * Generates batches of presigned URLs for multipart parts * * @remarks * Multipart uploads are uploaded in chunks or parts to individual presigned * URLs, similar to the one generated by /generate-presigned-put. The part * numbers provided must be between 1 and 10000. The total number of parts * will depend on the chunk size in bytes that you intend to use to upload * each chunk. For example a 12MB file may have 2 5MB chunks and a final * 2MB chunk, for part numbers 1, 2, and 3. * * This endpoint will return a presigned URL for each part number provided, * which you can then use to send PUT requests for the binary chunk corresponding * to that part. When the part is uploaded, the provider should return an * ETag for the part, and this should be stored along with the part number, * because this is needed to complete the multipart upload. * * You must have the correct permissions and CORS settings configured in your * external provider. We support AWS S3 as the default. See: * * https://meta.discourse.org/t/-/210469#s3-multipart-direct-uploads-4. * * An external file store must be set up and `enable_direct_s3_uploads` must * be set to true for this endpoint to function. * * */ async batchPresignMultipartParts( req: operations.BatchPresignMultipartPartsRequestBody, config?: AxiosRequestConfig ): Promise { if (!(req instanceof utils.SpeakeasyBase)) { req = new operations.BatchPresignMultipartPartsRequestBody(req); } const baseURL: string = utils.templateUrl( this.sdkConfiguration.serverURL, this.sdkConfiguration.serverDefaults ); const operationUrl: string = baseURL.replace(/\/$/, "") + "/uploads/batch-presign-multipart-parts.json"; let [reqBodyHeaders, reqBody]: [object, any] = [{}, null]; try { [reqBodyHeaders, reqBody] = utils.serializeRequestBody(req, "request", "json"); } catch (e: unknown) { if (e instanceof Error) { throw new Error(`Error serializing request body, cause: ${e.message}`); } } const client: AxiosInstance = this.sdkConfiguration.defaultClient; let globalSecurity = this.sdkConfiguration.security; if (typeof globalSecurity === "function") { globalSecurity = await globalSecurity(); } if (!(globalSecurity instanceof utils.SpeakeasyBase)) { globalSecurity = new shared.Security(globalSecurity); } const properties = utils.parseSecurityProperties(globalSecurity); const headers: RawAxiosRequestHeaders = { ...reqBodyHeaders, ...config?.headers, ...properties.headers, }; headers["Accept"] = "application/json"; headers["user-agent"] = this.sdkConfiguration.userAgent; const httpRes: AxiosResponse = await client.request({ validateStatus: () => true, url: operationUrl, method: "post", headers: headers, responseType: "arraybuffer", data: reqBody, ...config, }); const responseContentType: string = httpRes?.headers?.["content-type"] ?? ""; if (httpRes?.status == null) { throw new Error(`status code not found in response: ${httpRes}`); } const res: operations.BatchPresignMultipartPartsResponse = new operations.BatchPresignMultipartPartsResponse({ statusCode: httpRes.status, contentType: responseContentType, rawResponse: httpRes, }); const decodedRes = new TextDecoder().decode(httpRes?.data); switch (true) { case httpRes?.status == 200: if (utils.matchContentType(responseContentType, `application/json`)) { res.object = utils.objectToClass( JSON.parse(decodedRes), operations.BatchPresignMultipartPartsResponseBody ); } else { throw new errors.SDKError( "unknown content-type received: " + responseContentType, httpRes.status, decodedRes, httpRes ); } break; } return res; } /** * Completes a direct external upload * * @remarks * Completes an external upload initialized with /get-presigned-put. The * file will be moved from its temporary location in external storage to * a final destination in the S3 bucket. An Upload record will also be * created in the database in most cases. * * If a sha1-checksum was provided in the initial request it will also * be compared with the uploaded file in storage to make sure the same * file was uploaded. The file size will be compared for the same reason. * * You must have the correct permissions and CORS settings configured in your * external provider. We support AWS S3 as the default. See: * * https://meta.discourse.org/t/-/210469#s3-multipart-direct-uploads-4. * * An external file store must be set up and `enable_direct_s3_uploads` must * be set to true for this endpoint to function. * * */ async completeExternalUpload( req: operations.CompleteExternalUploadRequestBody, config?: AxiosRequestConfig ): Promise { if (!(req instanceof utils.SpeakeasyBase)) { req = new operations.CompleteExternalUploadRequestBody(req); } const baseURL: string = utils.templateUrl( this.sdkConfiguration.serverURL, this.sdkConfiguration.serverDefaults ); const operationUrl: string = baseURL.replace(/\/$/, "") + "/uploads/complete-external-upload.json"; let [reqBodyHeaders, reqBody]: [object, any] = [{}, null]; try { [reqBodyHeaders, reqBody] = utils.serializeRequestBody(req, "request", "json"); } catch (e: unknown) { if (e instanceof Error) { throw new Error(`Error serializing request body, cause: ${e.message}`); } } const client: AxiosInstance = this.sdkConfiguration.defaultClient; let globalSecurity = this.sdkConfiguration.security; if (typeof globalSecurity === "function") { globalSecurity = await globalSecurity(); } if (!(globalSecurity instanceof utils.SpeakeasyBase)) { globalSecurity = new shared.Security(globalSecurity); } const properties = utils.parseSecurityProperties(globalSecurity); const headers: RawAxiosRequestHeaders = { ...reqBodyHeaders, ...config?.headers, ...properties.headers, }; headers["Accept"] = "application/json"; headers["user-agent"] = this.sdkConfiguration.userAgent; const httpRes: AxiosResponse = await client.request({ validateStatus: () => true, url: operationUrl, method: "post", headers: headers, responseType: "arraybuffer", data: reqBody, ...config, }); const responseContentType: string = httpRes?.headers?.["content-type"] ?? ""; if (httpRes?.status == null) { throw new Error(`status code not found in response: ${httpRes}`); } const res: operations.CompleteExternalUploadResponse = new operations.CompleteExternalUploadResponse({ statusCode: httpRes.status, contentType: responseContentType, rawResponse: httpRes, }); const decodedRes = new TextDecoder().decode(httpRes?.data); switch (true) { case httpRes?.status == 200: if (utils.matchContentType(responseContentType, `application/json`)) { res.object = utils.objectToClass( JSON.parse(decodedRes), operations.CompleteExternalUploadResponseBody ); } else { throw new errors.SDKError( "unknown content-type received: " + responseContentType, httpRes.status, decodedRes, httpRes ); } break; } return res; } /** * Complete multipart upload * * @remarks * Completes the multipart upload in the external store, and copies the * file from its temporary location to its final location in the store. * All of the parts must have been uploaded to the external storage provider. * An Upload record will be completed in most cases once the file is copied * to its final location. * * You must have the correct permissions and CORS settings configured in your * external provider. We support AWS S3 as the default. See: * * https://meta.discourse.org/t/-/210469#s3-multipart-direct-uploads-4. * * An external file store must be set up and `enable_direct_s3_uploads` must * be set to true for this endpoint to function. * * */ async completeMultipart( req: operations.CompleteMultipartRequestBody, config?: AxiosRequestConfig ): Promise { if (!(req instanceof utils.SpeakeasyBase)) { req = new operations.CompleteMultipartRequestBody(req); } const baseURL: string = utils.templateUrl( this.sdkConfiguration.serverURL, this.sdkConfiguration.serverDefaults ); const operationUrl: string = baseURL.replace(/\/$/, "") + "/uploads/complete-multipart.json"; let [reqBodyHeaders, reqBody]: [object, any] = [{}, null]; try { [reqBodyHeaders, reqBody] = utils.serializeRequestBody(req, "request", "json"); } catch (e: unknown) { if (e instanceof Error) { throw new Error(`Error serializing request body, cause: ${e.message}`); } } const client: AxiosInstance = this.sdkConfiguration.defaultClient; let globalSecurity = this.sdkConfiguration.security; if (typeof globalSecurity === "function") { globalSecurity = await globalSecurity(); } if (!(globalSecurity instanceof utils.SpeakeasyBase)) { globalSecurity = new shared.Security(globalSecurity); } const properties = utils.parseSecurityProperties(globalSecurity); const headers: RawAxiosRequestHeaders = { ...reqBodyHeaders, ...config?.headers, ...properties.headers, }; headers["Accept"] = "application/json"; headers["user-agent"] = this.sdkConfiguration.userAgent; const httpRes: AxiosResponse = await client.request({ validateStatus: () => true, url: operationUrl, method: "post", headers: headers, responseType: "arraybuffer", data: reqBody, ...config, }); const responseContentType: string = httpRes?.headers?.["content-type"] ?? ""; if (httpRes?.status == null) { throw new Error(`status code not found in response: ${httpRes}`); } const res: operations.CompleteMultipartResponse = new operations.CompleteMultipartResponse({ statusCode: httpRes.status, contentType: responseContentType, rawResponse: httpRes, }); const decodedRes = new TextDecoder().decode(httpRes?.data); switch (true) { case httpRes?.status == 200: if (utils.matchContentType(responseContentType, `application/json`)) { res.object = utils.objectToClass( JSON.parse(decodedRes), operations.CompleteMultipartResponseBody ); } else { throw new errors.SDKError( "unknown content-type received: " + responseContentType, httpRes.status, decodedRes, httpRes ); } break; } return res; } /** * Creates a multipart external upload * * @remarks * Creates a multipart upload in the external storage provider, storing * a temporary reference to the external upload similar to /get-presigned-put. * * You must have the correct permissions and CORS settings configured in your * external provider. We support AWS S3 as the default. See: * * https://meta.discourse.org/t/-/210469#s3-multipart-direct-uploads-4. * * An external file store must be set up and `enable_direct_s3_uploads` must * be set to true for this endpoint to function. * * */ async createMultipartUpload( req: operations.CreateMultipartUploadRequestBody, config?: AxiosRequestConfig ): Promise { if (!(req instanceof utils.SpeakeasyBase)) { req = new operations.CreateMultipartUploadRequestBody(req); } const baseURL: string = utils.templateUrl( this.sdkConfiguration.serverURL, this.sdkConfiguration.serverDefaults ); const operationUrl: string = baseURL.replace(/\/$/, "") + "/uploads/create-multipart.json"; let [reqBodyHeaders, reqBody]: [object, any] = [{}, null]; try { [reqBodyHeaders, reqBody] = utils.serializeRequestBody(req, "request", "json"); } catch (e: unknown) { if (e instanceof Error) { throw new Error(`Error serializing request body, cause: ${e.message}`); } } const client: AxiosInstance = this.sdkConfiguration.defaultClient; let globalSecurity = this.sdkConfiguration.security; if (typeof globalSecurity === "function") { globalSecurity = await globalSecurity(); } if (!(globalSecurity instanceof utils.SpeakeasyBase)) { globalSecurity = new shared.Security(globalSecurity); } const properties = utils.parseSecurityProperties(globalSecurity); const headers: RawAxiosRequestHeaders = { ...reqBodyHeaders, ...config?.headers, ...properties.headers, }; headers["Accept"] = "application/json"; headers["user-agent"] = this.sdkConfiguration.userAgent; const httpRes: AxiosResponse = await client.request({ validateStatus: () => true, url: operationUrl, method: "post", headers: headers, responseType: "arraybuffer", data: reqBody, ...config, }); const responseContentType: string = httpRes?.headers?.["content-type"] ?? ""; if (httpRes?.status == null) { throw new Error(`status code not found in response: ${httpRes}`); } const res: operations.CreateMultipartUploadResponse = new operations.CreateMultipartUploadResponse({ statusCode: httpRes.status, contentType: responseContentType, rawResponse: httpRes, }); const decodedRes = new TextDecoder().decode(httpRes?.data); switch (true) { case httpRes?.status == 200: if (utils.matchContentType(responseContentType, `application/json`)) { res.object = utils.objectToClass( JSON.parse(decodedRes), operations.CreateMultipartUploadResponseBody ); } else { throw new errors.SDKError( "unknown content-type received: " + responseContentType, httpRes.status, decodedRes, httpRes ); } break; } return res; } /** * Creates an upload */ async createUpload( req: operations.CreateUploadRequestBody, config?: AxiosRequestConfig ): Promise { if (!(req instanceof utils.SpeakeasyBase)) { req = new operations.CreateUploadRequestBody(req); } const baseURL: string = utils.templateUrl( this.sdkConfiguration.serverURL, this.sdkConfiguration.serverDefaults ); const operationUrl: string = baseURL.replace(/\/$/, "") + "/uploads.json"; let [reqBodyHeaders, reqBody]: [object, any] = [{}, null]; try { [reqBodyHeaders, reqBody] = utils.serializeRequestBody(req, "request", "multipart"); } catch (e: unknown) { if (e instanceof Error) { throw new Error(`Error serializing request body, cause: ${e.message}`); } } const client: AxiosInstance = this.sdkConfiguration.defaultClient; let globalSecurity = this.sdkConfiguration.security; if (typeof globalSecurity === "function") { globalSecurity = await globalSecurity(); } if (!(globalSecurity instanceof utils.SpeakeasyBase)) { globalSecurity = new shared.Security(globalSecurity); } const properties = utils.parseSecurityProperties(globalSecurity); const headers: RawAxiosRequestHeaders = { ...reqBodyHeaders, ...config?.headers, ...properties.headers, }; headers["Accept"] = "application/json"; headers["user-agent"] = this.sdkConfiguration.userAgent; const httpRes: AxiosResponse = await client.request({ validateStatus: () => true, url: operationUrl, method: "post", headers: headers, responseType: "arraybuffer", data: reqBody, ...config, }); const responseContentType: string = httpRes?.headers?.["content-type"] ?? ""; if (httpRes?.status == null) { throw new Error(`status code not found in response: ${httpRes}`); } const res: operations.CreateUploadResponse = new operations.CreateUploadResponse({ statusCode: httpRes.status, contentType: responseContentType, rawResponse: httpRes, }); const decodedRes = new TextDecoder().decode(httpRes?.data); switch (true) { case httpRes?.status == 200: if (utils.matchContentType(responseContentType, `application/json`)) { res.object = utils.objectToClass( JSON.parse(decodedRes), operations.CreateUploadResponseBody ); } else { throw new errors.SDKError( "unknown content-type received: " + responseContentType, httpRes.status, decodedRes, httpRes ); } break; } return res; } /** * Initiates a direct external upload * * @remarks * Direct external uploads bypass the usual method of creating uploads * via the POST /uploads route, and upload directly to an external provider, * which by default is S3. This route begins the process, and will return * a unique identifier for the external upload as well as a presigned URL * which is where the file binary blob should be uploaded to. * * Once the upload is complete to the external service, you must call the * POST /complete-external-upload route using the unique identifier returned * by this route, which will create any required Upload record in the Discourse * database and also move file from its temporary location to the final * destination in the external storage service. * * You must have the correct permissions and CORS settings configured in your * external provider. We support AWS S3 as the default. See: * * https://meta.discourse.org/t/-/210469#s3-multipart-direct-uploads-4. * * An external file store must be set up and `enable_direct_s3_uploads` must * be set to true for this endpoint to function. * * */ async generatePresignedPut( req: operations.GeneratePresignedPutRequestBody, config?: AxiosRequestConfig ): Promise { if (!(req instanceof utils.SpeakeasyBase)) { req = new operations.GeneratePresignedPutRequestBody(req); } const baseURL: string = utils.templateUrl( this.sdkConfiguration.serverURL, this.sdkConfiguration.serverDefaults ); const operationUrl: string = baseURL.replace(/\/$/, "") + "/uploads/generate-presigned-put.json"; let [reqBodyHeaders, reqBody]: [object, any] = [{}, null]; try { [reqBodyHeaders, reqBody] = utils.serializeRequestBody(req, "request", "json"); } catch (e: unknown) { if (e instanceof Error) { throw new Error(`Error serializing request body, cause: ${e.message}`); } } const client: AxiosInstance = this.sdkConfiguration.defaultClient; let globalSecurity = this.sdkConfiguration.security; if (typeof globalSecurity === "function") { globalSecurity = await globalSecurity(); } if (!(globalSecurity instanceof utils.SpeakeasyBase)) { globalSecurity = new shared.Security(globalSecurity); } const properties = utils.parseSecurityProperties(globalSecurity); const headers: RawAxiosRequestHeaders = { ...reqBodyHeaders, ...config?.headers, ...properties.headers, }; headers["Accept"] = "application/json"; headers["user-agent"] = this.sdkConfiguration.userAgent; const httpRes: AxiosResponse = await client.request({ validateStatus: () => true, url: operationUrl, method: "post", headers: headers, responseType: "arraybuffer", data: reqBody, ...config, }); const responseContentType: string = httpRes?.headers?.["content-type"] ?? ""; if (httpRes?.status == null) { throw new Error(`status code not found in response: ${httpRes}`); } const res: operations.GeneratePresignedPutResponse = new operations.GeneratePresignedPutResponse({ statusCode: httpRes.status, contentType: responseContentType, rawResponse: httpRes, }); const decodedRes = new TextDecoder().decode(httpRes?.data); switch (true) { case httpRes?.status == 200: if (utils.matchContentType(responseContentType, `application/json`)) { res.object = utils.objectToClass( JSON.parse(decodedRes), operations.GeneratePresignedPutResponseBody ); } else { throw new errors.SDKError( "unknown content-type received: " + responseContentType, httpRes.status, decodedRes, httpRes ); } break; } return res; } }