Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@athenna/database",
"version": "5.41.0",
"version": "5.42.0",
"description": "The Athenna database handler for SQL/NoSQL.",
"license": "MIT",
"author": "João Lenon <lenon@athenna.io>",
Expand Down
57 changes: 52 additions & 5 deletions src/models/BaseModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,23 @@ export class BaseModel {
return query.update(data, cleanPersist)
}

/**
* Restore a soft deleted value from database.
*/
public static async restore<T extends typeof BaseModel>(
this: T,
where: Partial<InstanceType<T>>,
data: Partial<InstanceType<T>>
): Promise<InstanceType<T> | InstanceType<T>[]> {
const query = this.query()

if (where) {
query.where(where)
}

return query.restore(data)
}

/**
* Delete or soft delete a value in database.
*/
Expand Down Expand Up @@ -758,14 +775,44 @@ export class BaseModel {
*/
public async restore() {
const Model = this.constructor as any
const primaryKey = Model.schema().getMainPrimaryKeyProperty()
const schema = Model.schema()
const primaryKey = schema.getMainPrimaryKeyProperty()
const date = new Date()
const createdAt = schema.getCreatedAtColumn()
const updatedAt = schema.getUpdatedAtColumn()
const deletedAt = schema.getDeletedAtColumn()
const attributes = Model.isToSetAttributes ? Model.attributes() : {}

const restored = await Model.query()
.where(primaryKey, this[primaryKey])
.restore()
Object.keys(attributes).forEach(key => {
if (this[key]) {
return
}

this[key] = attributes[key]
})

if (createdAt && this[createdAt.property] === undefined) {
this[createdAt.property] = date
}

if (updatedAt && this[updatedAt.property] === undefined) {
this[updatedAt.property] = date
}

/**
* Forcing the deleted at column to be null to restore the model.
*/
if (deletedAt) {
this[deletedAt.property] = null
}

const data = this.dirty()

const where = { [primaryKey]: this[primaryKey] }
const restored = await Model.restore(where, data)

Object.keys(restored).forEach(key => (this[key] = restored[key]))

return this
return this.setOriginal()
}
}
18 changes: 13 additions & 5 deletions src/models/builders/ModelQueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -447,21 +447,29 @@ export class ModelQueryBuilder<
/**
* Restore one or multiple soft deleted models.
*/
public async restore() {
public async restore(data?: Partial<M>) {
this.setInternalQueries({ addSoftDelete: false })

if (!this.DELETED_AT_PROP) {
return
}

const date = new Date()
const updatedAt = this.schema.getUpdatedAtColumn()
const data = { [this.DELETED_AT_PROP]: null } as any
const attributes = this.isToSetAttributes ? this.Model.attributes() : {}

const parsed = this.schema.propertiesToColumnNames(
{ ...data, [this.DELETED_AT_PROP]: null } as any,
{
attributes
}
)

if (updatedAt) {
data[updatedAt.name] = new Date()
if (updatedAt && parsed[updatedAt.name] === undefined) {
parsed[updatedAt.name] = date
}

const updated = await super.update(data)
const updated = await super.update(parsed)

if (Is.Array(updated)) {
return this.generator.generateMany(updated)
Expand Down
192 changes: 192 additions & 0 deletions tests/unit/models/BaseModelTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,198 @@ export default class BaseModelTest {
assert.calledTimes(Database.driver.update, 2)
}

@Test()
public async shouldBeAbleToRestoreAModelAndSaveOtherChangesSimultaneously({ assert }: Context) {
Mock.when(Database.driver, 'find').resolve(undefined)
Mock.when(Database.driver, 'update').resolve({ id: '1', name: 'txsoura', deletedAt: null })
Mock.when(Database.driver, 'where').return(undefined)

const user = new User()

user.id = '1'
user.name = 'lenon'
user.email = 'lenon@athenna.io'
user.metadata1 = 'random-1'
user.metadata2 = 'random-2'
user.createdAt = new Date()
user.updatedAt = new Date()
user.deletedAt = new Date()

user.setOriginal()

user.name = 'txsoura'

await user.restore()

assert.isNull(user.deletedAt)
assert.deepEqual(user.name, 'txsoura')
assert.calledOnce(Database.driver.update)
}

@Test()
public async shouldBeAbleToRestoreAModelWithMultipleChanges({ assert }: Context) {
Mock.when(Database.driver, 'find').resolve(undefined)
Mock.when(Database.driver, 'update').resolve({
id: '1',
name: 'txsoura',
email: 'txsoura@athenna.io',
deletedAt: null
})
Mock.when(Database.driver, 'where').return(undefined)

const user = new User()

user.id = '1'
user.name = 'lenon'
user.email = 'lenon@athenna.io'
user.metadata1 = 'random-1'
user.metadata2 = 'random-2'
user.createdAt = new Date()
user.updatedAt = new Date()
user.deletedAt = new Date()

user.setOriginal()

user.name = 'txsoura'
user.email = 'txsoura@athenna.io'

await user.restore()

assert.isNull(user.deletedAt)
assert.deepEqual(user.name, 'txsoura')
assert.deepEqual(user.email, 'txsoura@athenna.io')
assert.calledOnce(Database.driver.update)
}

@Test()
public async shouldApplyAttributesWhenRestoringModel({ assert }: Context) {
Mock.when(Database.driver, 'find').resolve(undefined)
Mock.when(Database.driver, 'update').resolve({ id: '1', name: 'lenon', deletedAt: null })
Mock.when(Database.driver, 'where').return(undefined)

const user = new User()

user.id = '1'
user.name = 'lenon'
user.createdAt = new Date()
user.updatedAt = new Date()
user.deletedAt = new Date()

user.setOriginal()

await user.restore()

assert.isNull(user.deletedAt)
assert.calledOnce(Database.driver.update)
}

@Test()
public async shouldUpdateTimestampsWhenRestoringModel({ assert }: Context) {
Mock.when(Database.driver, 'find').resolve(undefined)
Mock.when(Database.driver, 'update').resolve({ id: '1', deletedAt: null })
Mock.when(Database.driver, 'where').return(undefined)

const user = new User()

user.id = '1'
user.name = 'lenon'
user.createdAt = new Date()
user.updatedAt = new Date()
user.deletedAt = new Date()

user.setOriginal()

await user.restore()

assert.isNull(user.deletedAt)
assert.calledOnce(Database.driver.update)
}

@Test()
public async shouldBeAbleToRestoreModelWithoutPriorChanges({ assert }: Context) {
Mock.when(Database.driver, 'find').resolve(undefined)
Mock.when(Database.driver, 'update').resolve({ id: '1', deletedAt: null })
Mock.when(Database.driver, 'where').return(undefined)

const user = new User()

user.id = '1'
user.name = 'lenon'
user.email = 'lenon@athenna.io'
user.metadata1 = 'random-1'
user.metadata2 = 'random-2'
user.createdAt = new Date()
user.updatedAt = new Date()
user.deletedAt = new Date()

user.setOriginal()

await user.restore()

assert.isNull(user.deletedAt)
assert.calledOnce(Database.driver.update)
}

@Test()
public async shouldBeAbleToRestoreModelUsingStaticMethod({ assert }: Context) {
Mock.when(Database.driver, 'find').resolve(undefined)
Mock.when(Database.driver, 'update').resolve({ id: '1', name: 'txsoura', deletedAt: null })
Mock.when(Database.driver, 'where').return(undefined)

const user = (await User.restore({ id: '1' }, { name: 'txsoura' })) as User

assert.isNull(user.deletedAt)
assert.deepEqual(user.name, 'txsoura')
assert.calledOnce(Database.driver.update)
}

@Test()
public async shouldBeAbleToRestoreMultipleModelsUsingStaticMethod({ assert }: Context) {
Mock.when(Database.driver, 'find').resolve(undefined)
Mock.when(Database.driver, 'update').resolve([
{ id: '1', name: 'txsoura', deletedAt: null },
{ id: '2', name: 'txsoura', deletedAt: null }
])
Mock.when(Database.driver, 'where').return(undefined)

const users = await User.restore({ name: 'lenon' }, { name: 'txsoura' })

assert.isArray(users)
assert.lengthOf(users as User[], 2)
assert.isNull((users as User[])[0].deletedAt)
assert.isNull((users as User[])[1].deletedAt)
assert.deepEqual((users as User[])[0].name, 'txsoura')
assert.deepEqual((users as User[])[1].name, 'txsoura')
assert.calledOnce(Database.driver.update)
}

@Test()
public async shouldSetOriginalAfterRestoringModel({ assert }: Context) {
Mock.when(Database.driver, 'find').resolve(undefined)
Mock.when(Database.driver, 'update').resolve({ id: '1', name: 'txsoura', deletedAt: null })
Mock.when(Database.driver, 'where').return(undefined)

const user = new User()

user.id = '1'
user.name = 'lenon'
user.metadata1 = 'random-1'
user.metadata2 = 'random-2'
user.createdAt = new Date()
user.updatedAt = new Date()
user.deletedAt = new Date()

user.setOriginal()

user.name = 'txsoura'

await user.restore()

assert.isFalse(user.isDirty())
assert.deepEqual(user.name, 'txsoura')
assert.isNull(user.deletedAt)
}

@Test()
public async shouldBeAbleToUseFakerProperty({ assert }: Context) {
assert.isTrue(BaseModel.faker.internet.email().includes('@'))
Expand Down
Loading