@codenameryuu/adonis-lucid-soft-deletes 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,40 +1,33 @@
1
1
  # @codenameryuu/adonis-lucid-soft-deletes
2
2
 
3
- This addon adds the functionality to soft deletes Lucid Models through the `deleted_at` flag in AdonisJS 7.
3
+ This addon adds the functionality to soft deletes Lucid Models through the `deleted_at` flag in AdonisJS.
4
4
 
5
- ## Introduction
5
+ ## Requirement
6
6
 
7
- Sometimes you may wish to "no-delete" a model from database.
8
- When models are soft deleted, they are not actually removed from your database.
9
- Instead, a `deleted_at` attribute is set on the model indicating the date
10
- and time at which the model was "deleted".
11
-
12
- :point_right: The SoftDeletes mixin will automatically add the `deleted_at` attribute
13
- as Luxon / DateTime instance.
7
+ - Adonis Js 7
8
+ - Lucid 22 or higher
14
9
 
15
10
  ## Installation
16
11
 
17
- Install it using `npm` , `yarn` or `pnpm` .
12
+ - Install the package
18
13
 
19
14
  ```bash
20
15
  yarn add @codenameryuu/adonis-lucid-soft-deletes
21
16
  ```
22
17
 
23
- After install call `configure` :
18
+ - Configure the package
24
19
 
25
20
  ```bash
26
21
  node ace configure @codenameryuu/adonis-lucid-soft-deletes
27
22
  ```
28
23
 
29
- ## Usage
30
-
31
- Make sure to register the provider inside `adonisrc.ts` file.
24
+ - Make sure to register the provider inside `adonisrc.ts` file.
32
25
 
33
26
  ```typescript
34
27
  providers: [
35
28
  // ...
36
29
  () => import('@codenameryuu/adonis-lucid-soft-deletes/provider'),
37
- ]
30
+ ],
38
31
  ```
39
32
 
40
33
  You should add the `deleted_at` column to your database tables for models with soft deletes.
@@ -43,8 +36,8 @@ You should add the `deleted_at` column to your database tables for models with s
43
36
  // migrations/1234566666_users.ts
44
37
  import { BaseSchema } from '@adonisjs/lucid/schema'
45
38
 
46
- export default class Users extends BaseSchema {
47
- protected tableName = 'users'
39
+ export default class extends BaseSchema {
40
+ protected tableName = 'products'
48
41
 
49
42
  async up() {
50
43
  this.schema.createTable(this.tableName, (table) => {
@@ -60,9 +53,9 @@ export default class Users extends BaseSchema {
60
53
 
61
54
  ```typescript
62
55
  import { compose } from '@adonisjs/core/helpers'
63
- import { SoftDeletes } from 'adonis-lucid-soft-deletes'
56
+ import { SoftDeletes } from '@codenameryuu/adonis-lucid-soft-deletes'
64
57
 
65
- export default class User extends compose(BaseModel, SoftDeletes) {
58
+ export default class Product extends compose(BaseModel, SoftDeletes) {
66
59
  // ...columns and props
67
60
  }
68
61
  ```
@@ -72,23 +65,23 @@ will be set to the current date and time. However, the model's database record w
72
65
 
73
66
  ```typescript
74
67
  import type { HttpContext } from '@adonisjs/core/http'
75
- import User from '#models/user'
68
+ import Product from '#models/product'
76
69
 
77
- export default class UsersController {
70
+ export default class ProductsController {
78
71
  /**
79
- * Delete user by id
80
- * DELETE /users/:id
72
+ * Delete product by id
73
+ * DELETE /products/:id
81
74
  */
82
- async destroy({ params, response }: HttpContext) {
83
- const user = await User.findOrFail(params.id)
84
- await user.delete()
75
+ async destroy({ request, response }: HttpContext) {
76
+ const product = await Product.findOrFail(request.input('id'))
77
+ await product.delete()
85
78
 
86
- return user // or response.noContent()
79
+ return product // or response.noContent()
87
80
  }
88
81
  }
89
82
  ```
90
83
 
91
- > :boom: Soft delete only works for model instances. `await User.query().delete()` as before
84
+ > :boom: Soft delete only works for model instances. `await Product.query().delete()` as before
92
85
  > will delete models from database
93
86
 
94
87
  :point_right: When querying a model that uses soft deletes, the soft deleted models
@@ -98,19 +91,19 @@ To determine if a given model instance has been soft deleted, you may use the `.
98
91
 
99
92
  ```typescript
100
93
  import type { HttpContext } from '@adonisjs/core/http'
101
- import User from '#models/user'
94
+ import Product from '#models/product'
102
95
 
103
- export default class UsersController {
96
+ export default class ProductsController {
104
97
  /**
105
- * Get user by id
106
- * GET /users/:id
98
+ * Get product by id
99
+ * GET /products/:id
107
100
  */
108
- async show({ params }: HttpContext) {
109
- const user = await User.withTrashed().where('id', params.id).firstOrFail()
110
- if (user.trashed) {
101
+ async show({ request, response }: HttpContext) {
102
+ const product = await Product.withTrashed().where('id', request.input('id')).firstOrFail()
103
+ if (product.trashed) {
111
104
  return response.forbidden()
112
105
  }
113
- return user
106
+ return product
114
107
  }
115
108
  }
116
109
  ```
@@ -119,9 +112,9 @@ export default class UsersController {
119
112
 
120
113
  ```typescript
121
114
  import { compose } from '@adonisjs/core/helpers'
122
- import { SoftDeletes } from 'adonis-lucid-soft-deletes'
115
+ import { SoftDeletes } from '@codenameryuu/adonis-lucid-soft-deletes'
123
116
 
124
- export default class User extends compose(BaseModel, SoftDeletes) {
117
+ export default class Product extends compose(BaseModel, SoftDeletes) {
125
118
  // ...columns and props
126
119
 
127
120
  @column.dateTime({ columnName: 'customDeletedAtColumn' })
@@ -138,23 +131,23 @@ The `restore` method will set the model's `deleted_at` column to `null` :
138
131
 
139
132
  ```ts
140
133
  import type { HttpContext } from '@adonisjs/core/http'
141
- import User from '#models/user'
134
+ import Product from '#models/product'
142
135
 
143
- export default class TrashUsersController {
136
+ export default class TrashProductsController {
144
137
  /**
145
- * Update trashed user by id
146
- * PUT /trash/users/:id
138
+ * Update trashed product by id
139
+ * PUT /trash/products/:id
147
140
  */
148
- async update({ params }: HttpContext) {
149
- const user = await User.withTrashed().where('id', params.id).firstOrFail()
150
- await user.restore()
141
+ async update({ request }: HttpContext) {
142
+ const product = await Product.withTrashed().where('id', request.input('id')).firstOrFail()
143
+ await product.restore()
151
144
 
152
- return user
145
+ return product
153
146
 
154
147
  // or
155
148
 
156
- await User.withTrashed().where('id', params.id).restore()
157
- await User.query().withTrashed().where('id', params.id).restore()
149
+ await Product.withTrashed().where('id', request.input('id')).restore()
150
+ await Product.query().withTrashed().where('id', request.input('id')).restore()
158
151
  }
159
152
  }
160
153
  ```
@@ -166,16 +159,16 @@ You may use the `.forceDelete()` method to permanently remove a soft deleted mod
166
159
 
167
160
  ```typescript
168
161
  import type { HttpContext } from '@adonisjs/core/http'
169
- import User from '#models/user'
162
+ import Product from '#models/product'
170
163
 
171
- export default class UsersController {
164
+ export default class ProductsController {
172
165
  /**
173
- * Delete user by id
174
- * DELETE /users/:id
166
+ * Delete product by id
167
+ * DELETE /products/:id
175
168
  */
176
- async destroy({ params, response }: HttpContext) {
177
- const user = await User.findOrFail(params.id)
178
- await user.forceDelete()
169
+ async destroy({ request, response }: HttpContext) {
170
+ const product = await Product.findOrFail(request.input('id'))
171
+ await product.forceDelete()
179
172
 
180
173
  return response.noContent()
181
174
  }
@@ -190,25 +183,19 @@ by calling the `.withTrashed()` method on the model:
190
183
 
191
184
  ```typescript
192
185
  import type { HttpContext } from '@adonisjs/core/http'
193
- import User from '#models/user'
186
+ import Product from '#models/product'
194
187
 
195
- export default class UsersController {
188
+ export default class ProductsController {
196
189
  /**
197
- * Get a list users
198
- * GET /users?withTrashed=1
190
+ * Get a list products
191
+ * GET /products?withTrashed=1
199
192
  */
200
193
  async index({ request }: HttpContext) {
201
- const usersQuery = request.input('withTrashed') ? User.withTrashed() : User.query()
202
-
203
- return usersQuery.exec()
204
-
205
- // or
206
-
207
- return User.query()
194
+ return Product.query()
208
195
  .if(request.input('withTrashed'), (query) => {
209
196
  query.withTrashed()
210
197
  })
211
- .exec()
198
+ .paginate(request.input('page', 1), request.input('perPage', 10))
212
199
  }
213
200
  }
214
201
  ```
@@ -219,15 +206,15 @@ The `.onlyTrashed()` method will retrieve **only** soft deleted models:
219
206
 
220
207
  ```typescript
221
208
  import type { HttpContext } from '@adonisjs/core/http'
222
- import User from '#models/user'
209
+ import Product from '#models/product'
223
210
 
224
- export default class TrashUsersController {
211
+ export default class TrashProductsController {
225
212
  /**
226
- * Get a list trashed users
227
- * GET /trash/users
213
+ * Get a list trashed products
214
+ * GET /trash/products
228
215
  */
229
216
  async index({ request }: HttpContext) {
230
- return User.onlyTrashed().exec()
217
+ return Product.onlyTrashed().paginate(request.input('page', 1), request.input('perPage', 10))
231
218
  }
232
219
  }
233
220
  ```
@@ -238,6 +225,10 @@ Methods `.withTrashed()` , `.onlyTrashed()` and `.restore()` also available
238
225
  in ModelQueryBuilder for models with soft delete, example:
239
226
 
240
227
  ```typescript
241
- await User.query().withTrashed().exec()
242
- await User.query().onlyTrashed().restore()
228
+ await Product.query().withTrashed().paginate(request.input('page', 1), request.input('perPage', 10))
229
+ await Product.query().onlyTrashed().paginate(request.input('page', 1), request.input('perPage', 10))
243
230
  ```
231
+
232
+ ## License
233
+
234
+ This package is open-sourced software licensed under the [MIT license](LICENSE.md).
@@ -0,0 +1,14 @@
1
+ /*
2
+ * adonis-lucid-soft-deletes
3
+ *
4
+ * (c) Lookin Anton <alsd@lookinlab.ru>
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
9
+ export async function configure(command) {
10
+ const codemods = await command.createCodemods();
11
+ await codemods.updateRcFile((rcFile) => {
12
+ rcFile.addProvider('@codenameryuu/adonis-lucid-soft-deletes/provider');
13
+ });
14
+ }
package/build/index.js CHANGED
@@ -1,128 +1,10 @@
1
- import {
2
- __decorateClass
3
- } from "./chunk-EUXUH3YW.js";
4
-
5
- // configure.ts
6
- async function configure(command) {
7
- const codemods = await command.createCodemods();
8
- await codemods.updateRcFile((rcFile) => {
9
- rcFile.addProvider("@codenameryuu/adonis-lucid-soft-deletes/provider");
10
- });
11
- }
12
-
13
- // src/mixin.ts
14
- import { DateTime } from "luxon";
15
- import { Exception } from "@adonisjs/core/exceptions";
16
- import { column, beforeFind, beforeFetch, beforePaginate } from "@adonisjs/lucid/orm";
17
- function SoftDeletes(superclass) {
18
- class ModelWithSoftDeletes extends superclass {
19
- static ignoreDeleted(query) {
20
- if (query["ignoreDeleted"] === false) {
21
- return;
22
- }
23
- const isGroupLimitQuery = query.clone().toQuery().includes("adonis_group_limit_counter");
24
- const deletedAtColumn = query.model.$getColumn("deletedAt")?.columnName;
25
- const queryIgnoreDeleted = isGroupLimitQuery ? query.knexQuery["_single"].table : query;
26
- queryIgnoreDeleted.whereNull(`${query.model.table}.${deletedAtColumn}`);
27
- }
28
- static ignoreDeletedPaginate([countQuery, query]) {
29
- countQuery["ignoreDeleted"] = query["ignoreDeleted"];
30
- this.ignoreDeleted(countQuery);
31
- }
32
- static disableIgnore(query) {
33
- if (query["ignoreDeleted"] === false) {
34
- return query;
35
- }
36
- query["ignoreDeleted"] = false;
37
- return query;
38
- }
39
- /**
40
- * Fetch all models without filter by deleted_at
41
- */
42
- static withTrashed() {
43
- const query = this.query();
44
- return this.disableIgnore(query);
45
- }
46
- /**
47
- * Fetch models only with deleted_at
48
- */
49
- static onlyTrashed() {
50
- const query = this.query();
51
- const deletedAtColumn = query.model.$getColumn("deletedAt")?.columnName;
52
- return this.disableIgnore(query).whereNotNull(`${query.model.table}.${deletedAtColumn}`);
53
- }
54
- /**
55
- * Force delete instance property
56
- */
57
- $forceDelete = false;
58
- /**
59
- * Computed trashed property
60
- */
61
- get trashed() {
62
- return this.deletedAt !== null;
63
- }
64
- /**
65
- * Override default $getQueryFor method
66
- */
67
- $getQueryFor(action, client) {
68
- const softDelete = async () => {
69
- this.deletedAt = DateTime.local();
70
- await this.save();
71
- };
72
- if (action === "delete" && !this.$forceDelete) {
73
- return { del: softDelete, delete: softDelete };
74
- }
75
- if (action === "insert") {
76
- return super.$getQueryFor(action, client);
77
- }
78
- return super.$getQueryFor(action, client);
79
- }
80
- /**
81
- * Override default delete method
82
- */
83
- async delete() {
84
- await super.delete();
85
- this.$isDeleted = this.$forceDelete;
86
- }
87
- /**
88
- * Restore model
89
- */
90
- async restore() {
91
- if (this.$isDeleted) {
92
- throw new Exception("Cannot restore a model instance is was force deleted", {
93
- code: "E_MODEL_FORCE_DELETED",
94
- status: 500
95
- });
96
- }
97
- if (!this.trashed) {
98
- return this;
99
- }
100
- this.deletedAt = null;
101
- await this.save();
102
- return this;
103
- }
104
- /**
105
- * Force delete model
106
- */
107
- async forceDelete() {
108
- this.$forceDelete = true;
109
- await this.delete();
110
- }
111
- }
112
- __decorateClass([
113
- column.dateTime()
114
- ], ModelWithSoftDeletes.prototype, "deletedAt", 2);
115
- __decorateClass([
116
- beforeFind(),
117
- beforeFetch()
118
- ], ModelWithSoftDeletes, "ignoreDeleted", 1);
119
- __decorateClass([
120
- beforePaginate()
121
- ], ModelWithSoftDeletes, "ignoreDeletedPaginate", 1);
122
- return ModelWithSoftDeletes;
123
- }
124
- export {
125
- SoftDeletes,
126
- configure
127
- };
128
- //# sourceMappingURL=index.js.map
1
+ /*
2
+ * adonis-lucid-soft-deletes
3
+ *
4
+ * (c) Lookin Anton <alsd@lookinlab.ru>
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
9
+ export { configure } from './configure.js';
10
+ export { SoftDeletes } from './src/mixin.js';
@@ -1,19 +1,19 @@
1
- import {
2
- extendModelQueryBuilder
3
- } from "../chunk-4FLDNTDF.js";
4
- import "../chunk-EUXUH3YW.js";
5
-
6
- // providers/lucid_soft_deletes_provider.ts
7
- var LucidSoftDeletesProvider = class {
8
- constructor(app) {
9
- this.app = app;
10
- }
11
- async boot() {
12
- const { ModelQueryBuilder } = await this.app.import("@adonisjs/lucid/orm");
13
- extendModelQueryBuilder(ModelQueryBuilder);
14
- }
15
- };
16
- export {
17
- LucidSoftDeletesProvider as default
18
- };
19
- //# sourceMappingURL=lucid_soft_deletes_provider.js.map
1
+ /*
2
+ * adonis-lucid-soft-deletes
3
+ *
4
+ * (c) Lookin Anton <alsd@lookinlab.ru>
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
9
+ import { extendModelQueryBuilder } from '../src/bindings/model_query_builder.js';
10
+ export default class LucidSoftDeletesProvider {
11
+ app;
12
+ constructor(app) {
13
+ this.app = app;
14
+ }
15
+ async boot() {
16
+ const { ModelQueryBuilder } = await this.app.import('@adonisjs/lucid/orm');
17
+ extendModelQueryBuilder(ModelQueryBuilder);
18
+ }
19
+ }
@@ -1,8 +1,41 @@
1
- import {
2
- extendModelQueryBuilder
3
- } from "../../chunk-4FLDNTDF.js";
4
- import "../../chunk-EUXUH3YW.js";
5
- export {
6
- extendModelQueryBuilder
7
- };
8
- //# sourceMappingURL=model_query_builder.js.map
1
+ /*
2
+ * adonis-lucid-soft-deletes
3
+ *
4
+ * (c) Lookin Anton <alsd@lookinlab.ru>
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
9
+ import { Exception } from '@adonisjs/core/exceptions';
10
+ /**
11
+ * Raises exception when model not with soft delete
12
+ */
13
+ function ensureModelWithSoftDeletes(model) {
14
+ if (!('ignoreDeleted' in model && 'ignoreDeletedPaginate' in model)) {
15
+ throw new Exception(`${model.name} model don't support Soft Deletes`, {
16
+ code: 'E_MODEL_SOFT_DELETE',
17
+ status: 500,
18
+ });
19
+ }
20
+ }
21
+ /**
22
+ * Define SoftDeletes binding to ModelQueryBuilder
23
+ */
24
+ export function extendModelQueryBuilder(builder) {
25
+ builder.macro('restore', async function () {
26
+ ensureModelWithSoftDeletes(this.model);
27
+ const deletedAtColumn = this.model.$getColumn('deletedAt')?.columnName;
28
+ if (!deletedAtColumn)
29
+ return;
30
+ await this.update({ [deletedAtColumn]: null });
31
+ });
32
+ builder.macro('withTrashed', function () {
33
+ ensureModelWithSoftDeletes(this.model);
34
+ return this.model.disableIgnore(this);
35
+ });
36
+ builder.macro('onlyTrashed', function () {
37
+ ensureModelWithSoftDeletes(this.model);
38
+ const deletedAtColumn = this.model.$getColumn('deletedAt')?.columnName;
39
+ return this.model.disableIgnore(this).whereNotNull(`${this.model.table}.${deletedAtColumn}`);
40
+ });
41
+ }
@@ -0,0 +1,129 @@
1
+ /*
2
+ * adonis-lucid-soft-deletes
3
+ *
4
+ * (c) Lookin Anton <alsd@lookinlab.ru>
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
9
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
10
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
11
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
12
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
13
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
14
+ };
15
+ import { DateTime } from 'luxon';
16
+ import { Exception } from '@adonisjs/core/exceptions';
17
+ import { column, beforeFind, beforeFetch, beforePaginate } from '@adonisjs/lucid/orm';
18
+ export function SoftDeletes(superclass) {
19
+ class ModelWithSoftDeletes extends superclass {
20
+ static ignoreDeleted(query) {
21
+ if (query['ignoreDeleted'] === false) {
22
+ return;
23
+ }
24
+ const isGroupLimitQuery = query.clone().toQuery().includes('adonis_group_limit_counter');
25
+ const deletedAtColumn = query.model.$getColumn('deletedAt')?.columnName;
26
+ const queryIgnoreDeleted = isGroupLimitQuery
27
+ ? query.knexQuery['_single'].table
28
+ : query;
29
+ queryIgnoreDeleted.whereNull(`${query.model.table}.${deletedAtColumn}`);
30
+ }
31
+ static ignoreDeletedPaginate([countQuery, query]) {
32
+ countQuery['ignoreDeleted'] = query['ignoreDeleted'];
33
+ this.ignoreDeleted(countQuery);
34
+ }
35
+ static disableIgnore(query) {
36
+ if (query['ignoreDeleted'] === false) {
37
+ return query;
38
+ }
39
+ query['ignoreDeleted'] = false;
40
+ return query;
41
+ }
42
+ /**
43
+ * Fetch all models without filter by deleted_at
44
+ */
45
+ static withTrashed() {
46
+ const query = this.query();
47
+ return this.disableIgnore(query);
48
+ }
49
+ /**
50
+ * Fetch models only with deleted_at
51
+ */
52
+ static onlyTrashed() {
53
+ const query = this.query();
54
+ const deletedAtColumn = query.model.$getColumn('deletedAt')?.columnName;
55
+ return this.disableIgnore(query).whereNotNull(`${query.model.table}.${deletedAtColumn}`);
56
+ }
57
+ /**
58
+ * Force delete instance property
59
+ */
60
+ $forceDelete = false;
61
+ /**
62
+ * Computed trashed property
63
+ */
64
+ get trashed() {
65
+ return this.deletedAt !== null;
66
+ }
67
+ /**
68
+ * Override default $getQueryFor method
69
+ */
70
+ $getQueryFor(action, client) {
71
+ /**
72
+ * Soft Delete
73
+ */
74
+ const softDelete = async () => {
75
+ this.deletedAt = DateTime.local();
76
+ await this.save();
77
+ };
78
+ if (action === 'delete' && !this.$forceDelete) {
79
+ return { del: softDelete, delete: softDelete };
80
+ }
81
+ if (action === 'insert') {
82
+ return super.$getQueryFor(action, client);
83
+ }
84
+ return super.$getQueryFor(action, client);
85
+ }
86
+ /**
87
+ * Override default delete method
88
+ */
89
+ async delete() {
90
+ await super.delete();
91
+ this.$isDeleted = this.$forceDelete;
92
+ }
93
+ /**
94
+ * Restore model
95
+ */
96
+ async restore() {
97
+ if (this.$isDeleted) {
98
+ throw new Exception('Cannot restore a model instance is was force deleted', {
99
+ code: 'E_MODEL_FORCE_DELETED',
100
+ status: 500,
101
+ });
102
+ }
103
+ if (!this.trashed) {
104
+ return this;
105
+ }
106
+ this.deletedAt = null;
107
+ await this.save();
108
+ return this;
109
+ }
110
+ /**
111
+ * Force delete model
112
+ */
113
+ async forceDelete() {
114
+ this.$forceDelete = true;
115
+ await this.delete();
116
+ }
117
+ }
118
+ __decorate([
119
+ column.dateTime()
120
+ ], ModelWithSoftDeletes.prototype, "deletedAt", void 0);
121
+ __decorate([
122
+ beforeFind(),
123
+ beforeFetch()
124
+ ], ModelWithSoftDeletes, "ignoreDeleted", null);
125
+ __decorate([
126
+ beforePaginate()
127
+ ], ModelWithSoftDeletes, "ignoreDeletedPaginate", null);
128
+ return ModelWithSoftDeletes;
129
+ }
@@ -1 +1,9 @@
1
- //# sourceMappingURL=querybuilder.js.map
1
+ /*
2
+ * adonis-lucid-soft-deletes
3
+ *
4
+ * (c) Lookin Anton <alsd@lookinlab.ru>
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
9
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@codenameryuu/adonis-lucid-soft-deletes",
3
- "description": "Addon for soft deletes Adonis JS 7 Lucid ORM",
4
- "version": "1.4.0",
3
+ "description": "Addon for soft deletes Adonis JS with Lucid ORM",
4
+ "version": "1.6.0",
5
5
  "author": "codenameryuu",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/codenameryuu/adonis-lucid-soft-deletes#readme",
@@ -29,15 +29,15 @@
29
29
  "format": "prettier --write .",
30
30
  "clean": "del-cli build",
31
31
  "precompile": "npm run lint && npm run clean",
32
- "compile": "tsup-node && tsc --emitDeclarationOnly --declaration",
32
+ "compile": "tsc",
33
33
  "build": "npm run compile",
34
+ "quick:test": "NODE_DEBUG=\"adonis-lucid-soft-deletes\" node --enable-source-maps --loader=ts-node/esm bin/test.ts",
34
35
  "pretest": "npm run lint",
35
36
  "test": "c8 npm run quick:test",
36
37
  "typecheck": "tsc --noEmit",
37
38
  "version": "npm run build",
38
39
  "prepublishOnly": "npm run build",
39
- "release": "np",
40
- "quick:test": "NODE_DEBUG=\"adonis-lucid-soft-deletes\" node --enable-source-maps --loader=ts-node/esm bin/test.ts"
40
+ "release": "np"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@adonisjs/assembler": "^7.7.0",
@@ -104,19 +104,5 @@
104
104
  "tests/**",
105
105
  "bin/**"
106
106
  ]
107
- },
108
- "tsup": {
109
- "entry": [
110
- "./index.ts",
111
- "./src/types/*.ts",
112
- "./src/bindings/model_query_builder.ts",
113
- "./providers/lucid_soft_deletes_provider.ts"
114
- ],
115
- "outDir": "./build",
116
- "clean": true,
117
- "format": "esm",
118
- "dts": false,
119
- "sourcemap": true,
120
- "target": "esnext"
121
107
  }
122
108
  }
@@ -1,32 +0,0 @@
1
- // src/bindings/model_query_builder.ts
2
- import { Exception } from "@adonisjs/core/exceptions";
3
- function ensureModelWithSoftDeletes(model) {
4
- if (!("ignoreDeleted" in model && "ignoreDeletedPaginate" in model)) {
5
- throw new Exception(`${model.name} model don't support Soft Deletes`, {
6
- code: "E_MODEL_SOFT_DELETE",
7
- status: 500
8
- });
9
- }
10
- }
11
- function extendModelQueryBuilder(builder) {
12
- builder.macro("restore", async function() {
13
- ensureModelWithSoftDeletes(this.model);
14
- const deletedAtColumn = this.model.$getColumn("deletedAt")?.columnName;
15
- if (!deletedAtColumn) return;
16
- await this.update({ [deletedAtColumn]: null });
17
- });
18
- builder.macro("withTrashed", function() {
19
- ensureModelWithSoftDeletes(this.model);
20
- return this.model.disableIgnore(this);
21
- });
22
- builder.macro("onlyTrashed", function() {
23
- ensureModelWithSoftDeletes(this.model);
24
- const deletedAtColumn = this.model.$getColumn("deletedAt")?.columnName;
25
- return this.model.disableIgnore(this).whereNotNull(`${this.model.table}.${deletedAtColumn}`);
26
- });
27
- }
28
-
29
- export {
30
- extendModelQueryBuilder
31
- };
32
- //# sourceMappingURL=chunk-4FLDNTDF.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/bindings/model_query_builder.ts"],"sourcesContent":["/*\n * adonis-lucid-soft-deletes\n *\n * (c) Lookin Anton <alsd@lookinlab.ru>\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport type {\n LucidModel,\n ModelQueryBuilderContract,\n ModelWithSoftDeletes,\n} from '@adonisjs/lucid/types/model'\n\nimport { Exception } from '@adonisjs/core/exceptions'\n\n/**\n * Raises exception when model not with soft delete\n */\nfunction ensureModelWithSoftDeletes(model: LucidModel) {\n if (!('ignoreDeleted' in model && 'ignoreDeletedPaginate' in model)) {\n throw new Exception(`${model.name} model don't support Soft Deletes`, {\n code: 'E_MODEL_SOFT_DELETE',\n status: 500,\n })\n }\n}\n\n/**\n * Define SoftDeletes binding to ModelQueryBuilder\n */\nexport function extendModelQueryBuilder(builder: any) {\n builder.macro('restore', async function (this: ModelQueryBuilderContract<LucidModel>) {\n ensureModelWithSoftDeletes(this.model)\n\n const deletedAtColumn = this.model.$getColumn('deletedAt')?.columnName\n if (!deletedAtColumn) return\n\n await this.update({ [deletedAtColumn]: null })\n })\n\n builder.macro('withTrashed', function (this: ModelQueryBuilderContract<ModelWithSoftDeletes>) {\n ensureModelWithSoftDeletes(this.model)\n return this.model.disableIgnore(this)\n })\n\n builder.macro('onlyTrashed', function (this: ModelQueryBuilderContract<ModelWithSoftDeletes>) {\n ensureModelWithSoftDeletes(this.model)\n\n const deletedAtColumn = this.model.$getColumn('deletedAt')?.columnName\n return this.model.disableIgnore(this).whereNotNull(`${this.model.table}.${deletedAtColumn}`)\n })\n}\n"],"mappings":";AAeA,SAAS,iBAAiB;AAK1B,SAAS,2BAA2B,OAAmB;AACrD,MAAI,EAAE,mBAAmB,SAAS,2BAA2B,QAAQ;AACnE,UAAM,IAAI,UAAU,GAAG,MAAM,IAAI,qCAAqC;AAAA,MACpE,MAAM;AAAA,MACN,QAAQ;AAAA,IACV,CAAC;AAAA,EACH;AACF;AAKO,SAAS,wBAAwB,SAAc;AACpD,UAAQ,MAAM,WAAW,iBAA6D;AACpF,+BAA2B,KAAK,KAAK;AAErC,UAAM,kBAAkB,KAAK,MAAM,WAAW,WAAW,GAAG;AAC5D,QAAI,CAAC,gBAAiB;AAEtB,UAAM,KAAK,OAAO,EAAE,CAAC,eAAe,GAAG,KAAK,CAAC;AAAA,EAC/C,CAAC;AAED,UAAQ,MAAM,eAAe,WAAiE;AAC5F,+BAA2B,KAAK,KAAK;AACrC,WAAO,KAAK,MAAM,cAAc,IAAI;AAAA,EACtC,CAAC;AAED,UAAQ,MAAM,eAAe,WAAiE;AAC5F,+BAA2B,KAAK,KAAK;AAErC,UAAM,kBAAkB,KAAK,MAAM,WAAW,WAAW,GAAG;AAC5D,WAAO,KAAK,MAAM,cAAc,IAAI,EAAE,aAAa,GAAG,KAAK,MAAM,KAAK,IAAI,eAAe,EAAE;AAAA,EAC7F,CAAC;AACH;","names":[]}
@@ -1,15 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __decorateClass = (decorators, target, key, kind) => {
4
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
6
- if (decorator = decorators[i])
7
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
8
- if (kind && result) __defProp(target, key, result);
9
- return result;
10
- };
11
-
12
- export {
13
- __decorateClass
14
- };
15
- //# sourceMappingURL=chunk-EUXUH3YW.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../configure.ts","../src/mixin.ts"],"sourcesContent":["/*\n * adonis-lucid-soft-deletes\n *\n * (c) Lookin Anton <alsd@lookinlab.ru>\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport type Configure from '@adonisjs/core/commands/configure'\n\nexport async function configure(command: Configure) {\n const codemods = await command.createCodemods()\n\n await codemods.updateRcFile((rcFile) => {\n rcFile.addProvider('@codenameryuu/adonis-lucid-soft-deletes/provider')\n })\n}\n","/*\n * adonis-lucid-soft-deletes\n *\n * (c) Lookin Anton <alsd@lookinlab.ru>\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport { DateTime } from 'luxon'\nimport type { NormalizeConstructor } from '@adonisjs/core/types/helpers'\nimport type { LucidModel, ModelQueryBuilderContract } from '@adonisjs/lucid/types/model'\nimport type { QueryClientContract } from '@adonisjs/lucid/types/database'\nimport { Exception } from '@adonisjs/core/exceptions'\nimport { column, beforeFind, beforeFetch, beforePaginate, BaseModel } from '@adonisjs/lucid/orm'\n\ntype ModelQueryBuilderContractWithIgnoreDeleted<\n T extends LucidModel,\n R = InstanceType<T>,\n> = ModelQueryBuilderContract<T, R> & {\n ignoreDeleted: boolean\n}\n\nexport function SoftDeletes<T extends NormalizeConstructor<typeof BaseModel>>(superclass: T) {\n class ModelWithSoftDeletes extends superclass {\n @beforeFind()\n @beforeFetch()\n static ignoreDeleted<Model extends typeof ModelWithSoftDeletes>(\n query: ModelQueryBuilderContractWithIgnoreDeleted<Model, InstanceType<Model>>\n ): void {\n if (query['ignoreDeleted'] === false) {\n return\n }\n const isGroupLimitQuery = query.clone().toQuery().includes('adonis_group_limit_counter')\n const deletedAtColumn = query.model.$getColumn('deletedAt')?.columnName\n\n const queryIgnoreDeleted = isGroupLimitQuery\n ? (query.knexQuery as any)['_single'].table\n : query\n\n queryIgnoreDeleted.whereNull(`${query.model.table}.${deletedAtColumn}`)\n }\n\n @beforePaginate()\n static ignoreDeletedPaginate<Model extends typeof ModelWithSoftDeletes>([countQuery, query]: [\n ModelQueryBuilderContractWithIgnoreDeleted<Model, InstanceType<Model>>,\n ModelQueryBuilderContractWithIgnoreDeleted<Model, InstanceType<Model>>,\n ]): void {\n countQuery['ignoreDeleted'] = query['ignoreDeleted']\n this.ignoreDeleted(countQuery)\n }\n\n static disableIgnore<Model extends typeof ModelWithSoftDeletes, Result = InstanceType<Model>>(\n this: Model,\n query: ModelQueryBuilderContractWithIgnoreDeleted<Model, Result>\n ): ModelQueryBuilderContractWithIgnoreDeleted<Model, Result> {\n if (query['ignoreDeleted'] === false) {\n return query\n }\n query['ignoreDeleted'] = false\n return query\n }\n\n /**\n * Fetch all models without filter by deleted_at\n */\n static withTrashed<Model extends typeof ModelWithSoftDeletes>(\n this: Model\n ): ModelQueryBuilderContractWithIgnoreDeleted<Model, InstanceType<T>> {\n const query = this.query() as ModelQueryBuilderContractWithIgnoreDeleted<\n Model,\n InstanceType<Model>\n >\n return this.disableIgnore(query)\n }\n\n /**\n * Fetch models only with deleted_at\n */\n static onlyTrashed<Model extends typeof ModelWithSoftDeletes>(\n this: Model\n ): ModelQueryBuilderContractWithIgnoreDeleted<Model, InstanceType<Model>> {\n const query = this.query() as ModelQueryBuilderContractWithIgnoreDeleted<\n Model,\n InstanceType<Model>\n >\n\n const deletedAtColumn = query.model.$getColumn('deletedAt')?.columnName\n return this.disableIgnore(query).whereNotNull(`${query.model.table}.${deletedAtColumn}`)\n }\n\n /**\n * Force delete instance property\n */\n $forceDelete = false\n\n /**\n * Soft deleted property\n */\n @column.dateTime()\n declare deletedAt?: DateTime | null\n\n /**\n * Computed trashed property\n */\n get trashed(): boolean {\n return this.deletedAt !== null\n }\n\n /**\n * Override default $getQueryFor method\n */\n $getQueryFor(\n action: 'insert' | 'update' | 'delete' | 'refresh',\n client: QueryClientContract\n ): any {\n /**\n * Soft Delete\n */\n const softDelete = async (): Promise<void> => {\n this.deletedAt = DateTime.local()\n await this.save()\n }\n\n if (action === 'delete' && !this.$forceDelete) {\n return { del: softDelete, delete: softDelete }\n }\n if (action === 'insert') {\n return super.$getQueryFor(action, client)\n }\n return super.$getQueryFor(action, client)\n }\n\n /**\n * Override default delete method\n */\n async delete(): Promise<void> {\n await super.delete()\n this.$isDeleted = this.$forceDelete\n }\n\n /**\n * Restore model\n */\n async restore(): Promise<this> {\n if (this.$isDeleted) {\n throw new Exception('Cannot restore a model instance is was force deleted', {\n code: 'E_MODEL_FORCE_DELETED',\n status: 500,\n })\n }\n if (!this.trashed) {\n return this\n }\n this.deletedAt = null\n await this.save()\n\n return this\n }\n\n /**\n * Force delete model\n */\n async forceDelete(): Promise<void> {\n this.$forceDelete = true\n await this.delete()\n }\n }\n return ModelWithSoftDeletes\n}\n"],"mappings":"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","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../providers/lucid_soft_deletes_provider.ts"],"sourcesContent":["/*\n * adonis-lucid-soft-deletes\n *\n * (c) Lookin Anton <alsd@lookinlab.ru>\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\n/// <reference path=\"../src/types/querybuilder.ts\" />\n\nimport type { ApplicationService } from '@adonisjs/core/types'\nimport { extendModelQueryBuilder } from '../src/bindings/model_query_builder.js'\n\nexport default class LucidSoftDeletesProvider {\n constructor(protected app: ApplicationService) {}\n\n async boot() {\n const { ModelQueryBuilder } = await this.app.import('@adonisjs/lucid/orm')\n extendModelQueryBuilder(ModelQueryBuilder)\n }\n}\n"],"mappings":";;;;;;AAcA,IAAqB,2BAArB,MAA8C;AAAA,EAC5C,YAAsB,KAAyB;AAAzB;AAAA,EAA0B;AAAA,EAEhD,MAAM,OAAO;AACX,UAAM,EAAE,kBAAkB,IAAI,MAAM,KAAK,IAAI,OAAO,qBAAqB;AACzE,4BAAwB,iBAAiB;AAAA,EAC3C;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}