All Projects → lookinlab → adonis-lucid-soft-deletes

lookinlab / adonis-lucid-soft-deletes

Licence: MIT license
Addon for soft deletes AdonisJS Lucid ORM

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to adonis-lucid-soft-deletes

Adonis Tdd Tutorial Demo
Stars: ✭ 22 (-60%)
Mutual labels:  adonisjs
Adonis Adminify
Admin dashboard based on AdonisJs + Adminify (based on vuetify)
Stars: ✭ 90 (+63.64%)
Mutual labels:  adonisjs
Moviepark
A Nuxt universal app with an Adonis 5 api server using the TMDb API for its movie catalog.
Stars: ✭ 32 (-41.82%)
Mutual labels:  adonisjs
Bj Decoupage Territorial
API pour récupérer les départements, communes, arrondissements et les quartiers du Bénin
Stars: ✭ 29 (-47.27%)
Mutual labels:  adonisjs
Create Adonis Ts App
Boilerplate to create a new AdonisJs typescript project
Stars: ✭ 63 (+14.55%)
Mutual labels:  adonisjs
Adonisjs Hackathon Starter
A boilerplate for AdonisJS web framework
Stars: ✭ 142 (+158.18%)
Mutual labels:  adonisjs
Adonuxt Template
[Deprecated] Starter template for Nuxt.js with AdonisJS.
Stars: ✭ 457 (+730.91%)
Mutual labels:  adonisjs
saas-react-starter-kit-boilerplate
SaaStr is a React SaaS boilerplate to kickstart your new SaaS adventure as fast as possible. Built on top of Adonis JS for the BackEnd and React Starter Kit for the Front-End
Stars: ✭ 100 (+81.82%)
Mutual labels:  adonisjs
Adonis Lucid Filter
Addon for filtering AdonisJS Lucid ORM
Stars: ✭ 67 (+21.82%)
Mutual labels:  adonisjs
Ace
Node.js framework for creating command line applications
Stars: ✭ 233 (+323.64%)
Mutual labels:  adonisjs
Adonisdocbr
Documentação completa em português brasileiro da versão 4.1 do Adonisjs
Stars: ✭ 33 (-40%)
Mutual labels:  adonisjs
Adonis pro
node.js 框架 adonisjs WEB应用:多人在线文章分享平台
Stars: ✭ 52 (-5.45%)
Mutual labels:  adonisjs
Leaguestats
📈 League of Legends Stats Web App
Stars: ✭ 172 (+212.73%)
Mutual labels:  adonisjs
Adminify
An Admin Dashboard based on Vuetify material
Stars: ✭ 923 (+1578.18%)
Mutual labels:  adonisjs
create-adonis-ts-app
Boilerplate to create a new AdonisJs typescript project
Stars: ✭ 94 (+70.91%)
Mutual labels:  adonisjs
Rest Admin
Restful Admin Dashboard Based on Vue and Boostrap 4
Stars: ✭ 565 (+927.27%)
Mutual labels:  adonisjs
Adonis Bumblebee
Api Transformer for AdonisJs Framework
Stars: ✭ 125 (+127.27%)
Mutual labels:  adonisjs
gerar-boletos
Biblioteca em Node.js para geração de boletos utilizando PDFKit.
Stars: ✭ 81 (+47.27%)
Mutual labels:  adonisjs
gavn
Invoice System for Freelancers as a Single Page Application built with AdonisJs and Vue.js
Stars: ✭ 54 (-1.82%)
Mutual labels:  adonisjs
Adonis Acl
demo app: https://github.com/enniel/adonis-acl-blog-demo
Stars: ✭ 195 (+254.55%)
Mutual labels:  adonisjs

Adonis Lucid Soft Deletes

npm-image license-image typescript-image

This addon adds the functionality to soft deletes Lucid Models

Works with @adonisjs/lucid@^15.*.*

Introduction

Sometimes you may wish to "no-delete" a model from database. When models are soft deleted, they are not actually removed from your database. Instead, a deleted_at attribute is set on the model indicating the date and time at which the model was "deleted".

👉 The SoftDeletes mixin will automatically add the deleted_at attribute as Luxon / DateTime instance.

Installation

Install it using npm or yarn.

# npm
npm i adonis-lucid-soft-deletes
node ace configure adonis-lucid-soft-deletes

# yarn
yarn add adonis-lucid-soft-deletes
node ace configure adonis-lucid-soft-deletes

Usage

Make sure to register the provider inside .adonisrc.json file.

{
  "providers": [
    "...other packages",
    "adonis-lucid-soft-deletes"
  ] 
}

For TypeScript projects add to tsconfig.json file:

{
  "compilerOptions": {
    "types": [
      "...other packages",
      "adonis-lucid-soft-deletes"
    ]
  } 
}

You should also add the deleted_at column to your database tables for models with soft deletes.

// migrations/1234566666_users.ts
import BaseSchema from '@ioc:Adonis/Lucid/Schema'

export default class Users extends BaseSchema {
  protected tableName = 'users'

  public async up() {
    this.schema.createTable(this.tableName, (table) => {
      // ...
      table.timestamp('deleted_at', { useTz: true }).nullable()
    })
  }
  // ...
}

Applying Soft Deletes to a Model

import { compose } from '@ioc:Adonis/Core/Helpers'
import { SoftDeletes } from '@ioc:Adonis/Addons/LucidSoftDeletes'

export default class User extends compose(BaseModel, SoftDeletes) {
  // ...columns and props

  // set custom `deletedAt` column name
  @column.dateTime({ columnName: 'customDeletedAtColumn' })
  public deletedAt?: DateTime | null
}

Now, when you call the .delete() method on the model, the deleted_at (customDeletedAtColumn) column will be set to the current date and time. However, the model's database record will be left in the table.

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'

export default class UsersController {
  /**
   * Delete user by id
   * DELETE /users/:id
   */
  public async destroy({ params, response }: HttpContextContract) {
    const user = await User.findOrFail(params.id)
    await user.delete()
    
    return user // or response.noContent()
  }
}

💥 Soft delete only works for model instances. await User.query().delete() as before will delete models from database

👉 When querying a model that uses soft deletes, the soft deleted models will automatically be excluded from all query results.

To determine if a given model instance has been soft deleted, you may use the .trashed getter:

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'

export default class UsersController {
  /**
   * Get user by id
   * GET /users/:id
   */
  public async show({ params }: HttpContextContract) {
    const user = await User.withTrashed().where('id', params.id).firstOrFail()
    if (user.trashed) {
      return response.forbidden()
    }
    return user
  }
}

Restoring Soft Deleted Models

To restore a soft deleted model, you may call the .restore() method on a model instance. Also, method .restore() exists after methods .withTrashed() and .onlyTrashed() The restore method will set the model's deleted_at column to null:

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'

export default class TrashUsersController {
  /**
   * Update trashed user by id
   * PUT /trash/users/:id
   */
  public async update({ params }: HttpContextContract) {
    const user = await User.withTrashed().where('id', params.id).firstOrFail()
    await user.restore()
    
    return user
    
    // or

    await User.withTrashed().where('id', params.id).restore()
    await User.query().withTrashed().where('id', params.id).restore()
  }
}

Permanently Deleting Models

Sometimes you may need to truly remove a model from your database. You may use the .forceDelete() method to permanently remove a soft deleted model from the database table:

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'

export default class UsersController {
  /**
   * Delete user by id
   * DELETE /users/:id
   */
  public async destroy({ params, response }: HttpContextContract) {
    const user = await User.findOrFail(params.id)
    await user.forceDelete()
    
    return response.noContent()
  }
}

Including Soft Deleted Models

As noted above, soft deleted models will automatically be excluded from query results. However, you may force soft deleted models to be included in a query's results by calling the .withTrashed() method on the model:

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'

export default class UsersController {
  /**
   * Get a list users
   * GET /users?withTrashed=1
   */
  public async index({ request }: HttpContextContract) {
    const usersQuery = request.input('withTrashed')
      ? User.withTrashed()
      : User.query()

    return usersQuery.exec()

    // or

    return User.query().if(request.input('withTrashed'), (query) => {
      query.withTrashed()
    }).exec()
  }
}

Retrieving only Soft Deleted Models

The .onlyTrashed() method will retrieve only soft deleted models:

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'

export default class TrashUsersController {
  /**
   * Get a list trashed users
   * GET /trash/users
   */
  public async index({ request }: HttpContextContract) {
    return User.onlyTrashed().exec()
  }
}

Soft Deletes methods

Methods .withTrashed(), .onlyTrashed() and .restore() also available in QueryBuilder for models with soft delete, example:

await User.query().withTrashed().exec()
await User.query().onlyTrashed().restore()
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].