A lightweight attachment management package for AdonisJS that allows you to easily associate files with your Lucid models.
npm i @adonisjs/attachment-lite
Configure the package using the node ace
command:
node ace add:attachment-lite
This command will:
- Add the provider to your
adonisrc.ts
file - Create a
config/attachment-lite.ts
configuration file
The default configuration is as follows:
import { defineConfig } from '@adonisjs/attachment-lite'
export default defineConfig({
disk: 'local',
defaultFolder: 'uploads',
validateMimeTypes: true,
})
You can modify these settings based on your application needs.
Use the @attachment
decorator to define attachment properties on your Lucid models:
import { BaseModel, column } from '@adonisjs/lucid/orm'
import { attachment } from '@adonisjs/attachment-lite'
import type { AttachmentContract } from '@adonisjs/attachment-lite/types'
export default class User extends BaseModel {
@column({ isPrimary: true })
declare id: number
@column()
declare email: string
@attachment()
declare avatar: AttachmentContract | null
}
You can create attachments from uploaded files:
import { Attachment } from '@adonisjs/attachment-lite'
// In your controller
public async update({ request, auth }) {
const user = auth.user!
const avatar = request.file('avatar')
if (avatar) {
// Create attachment from file
const attachment = new Attachment()
await attachment.fromFile(avatar)
user.avatar = attachment
await user.save()
}
return user
}
The package automatically:
- Stores files when a new attachment is set
- Deletes old files when an attachment is replaced
- Deletes files when a model is deleted
- Computes URLs for attachments when models are fetched
You can specify a custom disk and folder for each attachment:
@attachment({
disk: 's3',
folder: 'profile-pictures',
computeUrl: true
})
declare avatar: AttachmentContract | null
MIT