adonisjs / attachment-lite

Turn any field on your Lucid models to an attachment data type
MIT License
68 stars 20 forks source link

attachementLite.setOptions should override @attachment options #18

Closed Obapelumi closed 1 year ago

Obapelumi commented 2 years ago

Why this feature is required (specific use-cases will be appreciated)?

Sometimes you want to set disk/folder options for an attachment on the fly. For example, here I'm setting the folder option based on key, refId & entity

import { Attachment } from '@ioc:Adonis/Addons/AttachmentLite'
import { AuthContract } from '@ioc:Adonis/Addons/Auth'
import { TransactionClientContract } from '@ioc:Adonis/Lucid/Database'
import Entity from 'App/Models/System/Entity'
import Media from 'App/Models/System/Media'
import StoreMediaValidator from 'App/Validators/System/StoreMediaValidator'
import Env from '@ioc:Adonis/Core/Env'

export default class StoreMedia {
  public static async handle(
    { file, key, refId, entity }: StoreMediaValidator['schema']['props'],
    auth: AuthContract,
    client?: TransactionClientContract
  ) {
    const folder = `${Env.get('NODE_ENV')}/${entity}/${refId}/${key}`
    return await Media.create(
      {
        file: Attachment.fromFile(file).setOptions({ folder }),
        key,
        refId,
        entity: Entity[entity],
        createdBy: auth.user?.id
      },
      { client }
    )
  }
}

In this case the folder defaults to the one specified on the @attachment decorator in my Media model.

Have you tried any other work arounds?

Yes, I tried Attachment.fromFile(file).setOptions({ folder }).save() which uploads to the correct folder but I could not retrieve the correct path in order to persist it in the DB.

Are you willing to work on it with little guidance?

Yes, of course. Happy to take this on 😊

thetutlage commented 2 years ago

You can get it to work by defining the folder path as part of the name of the attachment.

import { cuid } from '@ioc:Adonis/Core/Helpers'

const folder = `${Env.get('NODE_ENV')}/${entity}/${refId}/${key}`
const name = `${folder}/${cuid()}.${file.extname}`

Attachment.fromFile(file, { name })
Obapelumi commented 2 years ago

Oh great. Thanks!

Obapelumi commented 2 years ago

You can get it to work by defining the folder path as part of the name of the attachment.

Tried this but Attachment.fromFile seems to only take one argument so it did not work.

Eventually got to work by doing:

const attachment = Attachment.fromFile(file).setOptions({ folder })
    const attachment = Attachment.fromFile(file).setOptions({ folder })
    attachment.save()
    await Media.query()
      .where({ id: media.id })
      .update({ file: JSON.stringify(attachment) })
stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.