Socket
Socket
Sign inDemoInstall

@jrmc/adonis-attachment

Package Overview
Dependencies
Maintainers
0
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@jrmc/adonis-attachment

Turn any field on your Lucid model to an attachment data type


Version published
Weekly downloads
88
increased by25.71%
Maintainers
0
Weekly downloads
 
Created
Source

AdonisJS attachment

This package is currently development and will replace attachment-advanced for AdonisJS 6.

Roadmap

  • attachment file by file system
  • save meta data
  • variantes
    • images
    • documents
    • videos
  • command regenerate
  • adonis-drive/flydrive
  • jobs queue
  • edge component
  • serialize

File sytem

Upload file in public folder.

Meta data list (if available)

  • extension name
  • size
  • dimension (width, height)
  • created date
  • orientation
  • mime type
  • gps

Variants

Configure differents images sizes and formats

Regenerate

Regenerate variantes files

Drive

Use drive for private file and cloud services

Jobs queue

Couple with a job queue (recommended, optional)

Setup

Install and configure the package:

node ace add @jrmc/adonis-attachment

Or:

npm i @jrmc/adonis-attachment
node ace configure @jrmc/adonis-attachment

Usage

Often times, the size of the image metadata could exceed the allowable length of an SQL String data type. So, it is recommended to create/modify the column which will hold the metadata to use a JSON data type.

If you are creating the column for the first time, make sure that you use the JSON data type. Example:

  // Within the migration file

  protected tableName = 'users'

  public async up() {
    this.schema.createTable(this.tableName, (table) => {
      table.increments()
      table.json('avatar') // <-- Use a JSON data type
    })
  }

If you already have a column for storing image paths/URLs, you need to create a new migration and alter the column definition to a JSON data type. Example:

# Create a new migration file
node ace make:migration change_avatar_column_to_json --table=users
  // Within the migration file

  protected tableName = 'users'

  public async up() {
    this.schema.alterTable(this.tableName, (table) => {
      table.json('avatar').alter() // <-- Alter the column definition
    })
  }

Next, in the model, import the attachment decorator, Attachmentable mixin and the Attachment type from the package.

Make sure NOT to use the @column decorator when using the @attachment decorator.

import { BaseModel } from '@adonisjs/lucid/orm'
import { compose } from '@adonisjs/core/helpers'
import { attachment, Attachmentable } from '@jrmc/adonis-attachment'
import type { Attachment } from '@jrmc/adonis-attachment/types/attachment'

class User extends compose(BaseModel, Attachmentable) {
  @attachment()
  declare avatar: Attachment
}

Now you can create an attachment from the user uploaded file as follows.

import { attachmentManager } from '@jrmc/adonis-attachment'

class UsersController {
  public store({ request }: HttpContext) {
    const avatar = request.file('avatar')!
    const user = new User()

    user.avatar = await attachmentManager.createFromFile(avatar)
    // user.avatar = await attachmentManager.createFromBuffer(buffer, 'photo.jpg')
    await user.save()
  }
}

Specifying subfolder

You can also store files inside the subfolder by defining the folder property as follows.

class User extends BaseModel {
  @attachment({ folder: 'uploads/avatars' })
  declare avatar: Attachment
}

Specifying variants

It is possible to limit the variants on an attachment

class User extends BaseModel {
  @attachment({
    variants: ['thumbnail', 'medium', 'large']
  })
  declare avatar: Attachment
}

URLs

user.avatar.getUrl()
user.avatar.getUrl('thumbnail')
// or await user.avatar.getVariant('thumbnail').getUrl()
  <img src="{{ user.avatar.getUrl('thumbnail') }}" loading="lazy" alt="" />

Configuration

Configuration for variants files (config/attachment.ts)

import { defineConfig } from '@jrmc/adonis-attachment'
import app from '@adonisjs/core/services/app'
import sharp from 'sharp'

export default defineConfig({
  basePath: app.publicPath(),
  converters: [
    {
      key: 'thumbnail',
      converter: () => import('@jrmc/adonis-attachment/converters/image_converter'),
      options: {
        resize: 300,
        format: 'webp',
      }
    },
    {
      key: 'medium',
      converter: () => import('@jrmc/adonis-attachment/converters/image_converter'),
      options: {
        format: 'jpeg',
        resize: { // https://sharp.pixelplumbing.com/api-resize
          width: 400,
          height: 400,
          fit: sharp.fit.cover,
          position: 'top'
        },
      }
    },
    {
      key: 'large',
      converter: () => import('@jrmc/adonis-attachment/converters/image_converter'),
      options: {
        resize: 1024,
        format: {
          format: 'png',
          options: {
            quality: 80
          }
        }

      }
    },
  ]
})

Variant image is generate by sharp module

Options resize is number or object(options) details in documentation : sharp api resize

Options format is string or array [ format, options ] details in documentation : sharp api outpout

Keywords

FAQs

Package last updated on 04 Jul 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc