UNPKG

dobo

Version:

DBMS for Bajo Framework

37 lines (34 loc) 1.5 kB
import { mergeAttachmentInfo, getAttachmentPath } from './_util.js' const action = 'createAttachment' async function createAttachment (...args) { const { createThumbnail } = this.app.bajoExtra const { thumbSizes: size } = this.app.dobo.config.default.attachment if (!this.options.attachment) return if (args.length === 0) return this.action(action, ...args) const [id, opts = {}] = args const { fs } = this.app.lib const { isEmpty, last } = this.app.lib._ const { source, field = 'file', file, fullPath, stats, mimeType, req } = opts if (isEmpty(file)) return if (!source) throw this.plugin.error('isMissing%s', this.plugin.t('field.source')) const [, filename] = last(source.split('/')).split('@') if (isEmpty(filename)) return const baseDir = await getAttachmentPath.call(this, id, field, file, { dirOnly: true }) let dir = `${baseDir}/${field}` if ((field || '').endsWith('[]')) dir = `${baseDir}/${field.replace('[]', '')}` const dest = `${dir}/${file}`.replaceAll('//', '/') await fs.ensureDir(dir) await fs.copy(source, dest) try { if (createThumbnail) await createThumbnail(dest, { dir: `${dir}/_tn`, size, format: ['.png'] }) } catch (err) {} const rec = { field: field === '' ? undefined : field, dir, file } await mergeAttachmentInfo.call(this, rec, dest, { mimeType, fullPath, stats }) if (!opts.noFlash && req && req.flash) req.flash('notify', req.t('attachmentUploaded')) return rec } export default createAttachment