npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@inovan.do/adonis-crud

v0.1.47

Published

A crud abstraction for AdonisJs

Downloads

26

Readme

adonis-crud

Advanced abstraction to use with Adonis Framework

Contents

Installation

npm install @inovan.do/adonis-crud

Configuration

Install Lucid Orm

As informed here Adonis DataBase Introduction

Install Auth

As informed here Adonis Auth Introduction

auth install orientation.

Also install the hash dependencie available-hashers

npm i phc-argon2

Configure package

node ace configure adonis-crud

This should update your .adonisrc.json, tsconfig.json and add a list of other files: File Genereted

Usage Example

Let's create some come.

Create the route for the resource

  • in routes.ts add
Route.resource('/posts', 'PostController')

Create the migration to the model

node ace make:migration Posts

import BaseSchema from '@ioc:Adonis/Lucid/Schema'
export default class extends BaseSchema {
  protected tableName = 'posts'

  public async up() {
    this.schema.createTable(this.tableName, (table) => {
      table.increments('id')
      table.string('title').notNullable()
      table.string('content').notNullable()
      table.boolean('status').defaultTo(true)
      table.timestamp('created_at', { useTz: true })
      table.timestamp('updated_at', { useTz: true })
    })
  }

  public async down() {
    this.schema.dropTable(this.tableName)
  }
}

Migration and seeders

Create database initial structure

  node ace migration:run

Seeds Initial Data

  node ace make:model Post

Create the model to persist data to the database

  node ace make:model Post

Fulfill as needed

import { DateTime } from 'luxon'
import { BaseModel, column } from '@ioc:Adonis/Lucid/Orm'

export default class Post extends BaseModel {
 @column({ isPrimary: true })
  public id: number

  @column.dateTime({ autoCreate: true })
  public createdAt: DateTime

  @column.dateTime({ autoCreate: true, autoUpdate: true })
  public updatedAt: DateTime

  @column()
  public status: boolean

  @column()
  public title: string

  @column()
  public content: string
}

Create your repository to deal with your model using the decorator provided

import Event from '@ioc:Adonis/Core/Event'
import CrudRepository, { CrudRepositoryInterface } from '@ioc:AdonisCrud/Crud/Repository'
import User from 'App/Models/Post'

@CrudRepository<Post>({
  event: Event,
  model: Post,
  selectFields: ['id', 'title', 'content'],
 
})
export default class PostRepository implements CrudRepositoryInterface<Post> {}

Crud repository props

| Property | Description | Required?| |------------------| -----------| -----------| | event | Event emiter from Adonis to be used in hooks features | ☑| | model | Model | ☑| | selectFields | Array of fields to be used in select | ☑|

Create your transformer

import { TransformerAbstract } from '@ioc:Adonis/Addons/Bumblebee'
export default class PostTransformer extends TransformerAbstract {
  public transform(model) {
    return {
      id: model.id,
      status: model.status,
      title: model.title,
      content: model.content,
      createdAt: model.createdAt,
    }
  }
}

Here you can format or transform your data, format a date field, make a computed property....

Create your controller and use the decorator provided

import Crud, { CrudControllerInterface, OptionsCrud } from '@ioc:AdonisCrud/Crud/Controller'
import Post from 'App/Models/Post'
import PostRepository from '@ioc:PostRepository'
import BaseTransformer from 'App/Transformers/BaseTransformer'

@Crud<Post>({
  repository: PostRepository,
  storeProps: ['title','content'],
  updateProps: ['content'],
  transformer: BaseTransformer,
  validators: {
    store: '', //Adonis validator class
    update: ''
  }
})
export default class PostsController<Post> implements CrudControllerInterface<Post> {
  options: OptionsCrud<Post>
}

Crud decorator options

| Property | Description | Required?| |-----------------| -----------| -----------| | repository | Repository used to deal with your model data.| ☑| | storeProps | Allow properties to create your model.| ☑| | updateProps | Allow properties to update your model.|☑| | transformer | Adonis bublebee class to trasform data | ☑| | validators | Validator class for each method used to store and update ] |☐|

If a not allowed param is provided in store or update request a exception will be returned.

If a validator object is not provided validation will not be applied to store and update methods.

Features

  • ☑ Crud Abstraction
  • ☑ Validators
  • ☑ Events (on update, on delete, on create)
  • ☑ Intercept flow and develop your own bussines logic
  • ☑ Apply Scoped Queries
  • ☑ Transformer with includes (join relationship automagically). Thanks to adonis-bublebee-ts.
  • ☑ Generate report csv/ pdf.
  • ☑ ACL based on Adonis ACL.

Create

  • Validate data to create based on Adonis Validators.
  • Bulk Insert

Read

  • Default pagination
  • Feature includes (add relationship to return data)
  • Query builder from request params
  • Feature All (get all itens)
  • Configurable select fields
  • Configurable order

Update

  • Validate update props based on adonis validators
  • Bulk update

Delete

  • Default soft delete strategy
  • Bulk delete

Dependencies

File Generated by Adonis Crud

BaseCrudModel

import { DateTime } from 'luxon'
import { BaseModel, column } from '@ioc:Adonis/Lucid/Orm'

export default class BaseCrudModel extends BaseModel {
  @column({ isPrimary: true })
  public id: number

  @column.dateTime({ autoCreate: true })
  public createdAt: DateTime

  @column.dateTime({ autoCreate: true, autoUpdate: true })
  public updatedAt: DateTime

  @column()
  public status: boolean
}

Profile

import { column } from '@ioc:Adonis/Lucid/Orm'
import BaseCrudModel from './BaseCrudModel'
export default class Profile extends BaseCrudModel {
  @column()
  public name: string
}

User

import { DateTime } from 'luxon'
import Hash from '@ioc:Adonis/Core/Hash'
import { column, beforeSave, ManyToMany, manyToMany } from '@ioc:Adonis/Lucid/Orm'
import BaseCrudModel from './BaseCrudModel'
import Profile from './Profile'

export default class User extends BaseCrudModel {
  @column()
  public name: string

  @column()
  public email: string

  @column({ serializeAs: null })
  public password: string

  @column()
  public status: boolean

  @column()
  public rememberMeToken?: string

  @column.dateTime({ autoCreate: true })
  public createdAt: DateTime

  @column.dateTime({ autoCreate: true, autoUpdate: true })
  public updatedAt: DateTime

  @column.dateTime()
  public deletedAt: DateTime

  @beforeSave()
  public static async hashPassword(user: User) {
    if (user.$dirty.password) {
      user.password = await Hash.make(user.password)
    }
  }

  @manyToMany(() => Profile, {
    localKey: 'id',
    pivotForeignKey: 'user_id',
    relatedKey: 'id',
    pivotRelatedForeignKey: 'profile_id',
    pivotTable: 'user_profiles',
  })
  public profiles: ManyToMany<typeof Profile>
}

Query Builder

Contributing

  • Clone this repo
  • Install dependencies: npm install
  • Implement your feature
  • build de code: yarn build