UNPKG

@wordpress/media-utils

Version:
8 lines (7 loc) 2.96 kB
{ "version": 3, "sources": ["../../src/utils/sideload-media.ts"], "sourcesContent": ["/**\n * WordPress dependencies\n */\nimport { __, sprintf } from '@wordpress/i18n';\n\n/**\n * Internal dependencies\n */\nimport type {\n\tOnChangeHandler,\n\tOnErrorHandler,\n\tCreateSideloadFile,\n\tRestAttachment,\n} from './types';\nimport { sideloadToServer } from './sideload-to-server';\nimport { UploadError } from './upload-error';\n\nconst noop = () => {};\n\ninterface SideloadMediaArgs {\n\t// Additional data to include in the request.\n\tadditionalData?: CreateSideloadFile;\n\t// File to sideload.\n\tfile: File;\n\t// Attachment ID.\n\tattachmentId: RestAttachment[ 'id' ];\n\t// Function called when an error happens.\n\tonError?: OnErrorHandler;\n\t// Function called each time a file or a temporary representation of the file is available.\n\tonFileChange?: OnChangeHandler;\n\t// Abort signal.\n\tsignal?: AbortSignal;\n}\n\n/**\n * Uploads a file to the server without creating an attachment.\n *\n * @param $0 Parameters object passed to the function.\n * @param $0.file Media File to Save.\n * @param $0.attachmentId Parent attachment ID.\n * @param $0.additionalData Additional data to include in the request.\n * @param $0.signal Abort signal.\n * @param $0.onFileChange Function called each time a file or a temporary representation of the file is available.\n * @param $0.onError Function called when an error happens.\n */\nexport async function sideloadMedia( {\n\tfile,\n\tattachmentId,\n\tadditionalData = {},\n\tsignal,\n\tonFileChange,\n\tonError = noop,\n}: SideloadMediaArgs ) {\n\ttry {\n\t\tconst attachment = await sideloadToServer(\n\t\t\tfile,\n\t\t\tattachmentId,\n\t\t\tadditionalData,\n\t\t\tsignal\n\t\t);\n\t\tonFileChange?.( [ attachment ] );\n\t} catch ( error ) {\n\t\tlet message;\n\t\tif ( error instanceof Error ) {\n\t\t\tmessage = error.message;\n\t\t} else {\n\t\t\tmessage = sprintf(\n\t\t\t\t// translators: %s: file name\n\t\t\t\t__( 'Error while sideloading file %s to the server.' ),\n\t\t\t\tfile.name\n\t\t\t);\n\t\t}\n\t\tonError(\n\t\t\tnew UploadError( {\n\t\t\t\tcode: 'GENERAL',\n\t\t\t\tmessage,\n\t\t\t\tfile,\n\t\t\t\tcause: error instanceof Error ? error : undefined,\n\t\t\t} )\n\t\t);\n\t}\n}\n"], "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,kBAA4B;AAW5B,gCAAiC;AACjC,0BAA4B;AAE5B,IAAM,OAAO,MAAM;AAAC;AA4BpB,eAAsB,cAAe;AAAA,EACpC;AAAA,EACA;AAAA,EACA,iBAAiB,CAAC;AAAA,EAClB;AAAA,EACA;AAAA,EACA,UAAU;AACX,GAAuB;AACtB,MAAI;AACH,UAAM,aAAa,UAAM;AAAA,MACxB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACD;AACA,mBAAgB,CAAE,UAAW,CAAE;AAAA,EAChC,SAAU,OAAQ;AACjB,QAAI;AACJ,QAAK,iBAAiB,OAAQ;AAC7B,gBAAU,MAAM;AAAA,IACjB,OAAO;AACN,oBAAU;AAAA;AAAA,YAET,gBAAI,gDAAiD;AAAA,QACrD,KAAK;AAAA,MACN;AAAA,IACD;AACA;AAAA,MACC,IAAI,gCAAa;AAAA,QAChB,MAAM;AAAA,QACN;AAAA,QACA;AAAA,QACA,OAAO,iBAAiB,QAAQ,QAAQ;AAAA,MACzC,CAAE;AAAA,IACH;AAAA,EACD;AACD;", "names": [] }