-
-
Save adrianolsk/b83f2a7a7c168c98f9a989b826f1dfe9 to your computer and use it in GitHub Desktop.
Knex.js Gotchas!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* SINPPET FOR DELETED & DELETED AT SUPPORT IN KNEX.JS | |
inspired from Sequlize.js 'paranoid' schema option, | |
don't delete rows from database, ever. | |
*/ | |
/* In Table Definition */ | |
knex.schema.createTable('TABLE_NAME', function(table) { | |
table.boolean('deleted').defaultsTo(false).notNullable(); | |
table.dateTime('deleted_at'); | |
}); | |
/* To Emulate Delete */ | |
delete(id) { | |
return db.table('accounts').where({ id: id}) | |
.returning('deleted') | |
.update({ | |
deleted: true, | |
deleted_at: new Date() | |
}); | |
} | |
/* Then When Handling Read or Search */ | |
findAll() { | |
return db.select().from('TABLE_NAME').where({ deleted: false }); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* CORRECT HANDLING OF TIMESTAMPS IN KNEX.JS */ | |
knex.schema.createTable('TABLE_NAME', function(table) { | |
table.timestamps(true, true); // Adds 'created_at' & 'updated_at' with both not nullable & default-ing to Date.now(); | |
table.timestamps(); // Just adds 'created_at' & 'updated_at' with default null | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment