File size: 1,201 Bytes
3206347 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
import { Model } from 'objection';
const DELETED_COLUMN_NAME = 'deleted_at';
const supportsSoftDeletion = (modelClass) => {
return modelClass.jsonSchema.properties.deletedAt;
};
const buildQueryBuidlerForClass = () => {
return (modelClass) => {
const qb = Model.QueryBuilder.forClass.call(
ExtendedQueryBuilder,
modelClass
);
qb.onBuild((builder) => {
if (
!builder.context().withSoftDeleted &&
supportsSoftDeletion(qb.modelClass())
) {
builder.whereNull(
`${qb.modelClass().tableName}.${DELETED_COLUMN_NAME}`
);
}
});
return qb;
};
};
class ExtendedQueryBuilder extends Model.QueryBuilder {
static forClass = buildQueryBuidlerForClass();
delete() {
if (supportsSoftDeletion(this.modelClass())) {
return this.patch({
[DELETED_COLUMN_NAME]: new Date().toISOString(),
});
}
return super.delete();
}
hardDelete() {
return super.delete();
}
withSoftDeleted() {
this.context().withSoftDeleted = true;
return this;
}
restore() {
return this.patch({
[DELETED_COLUMN_NAME]: null,
});
}
}
export default ExtendedQueryBuilder;
|