From 8e46d02ed13af7d61dea06d774823e01d046a99d Mon Sep 17 00:00:00 2001 From: Romain Lanz Date: Wed, 2 Jan 2019 10:10:56 +0100 Subject: [PATCH] feat: add NoTimestamp trait + ConvertEmptyStringsToNull middleware (#30) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hey! 👋 This PR add some middleware and traits by default. **Middleware**: - `AllowGuestOnly` throws an exception if you are authenticated. - `ConvertEmptyStringsToNull` converts empty strings in the request body to `null` **Trait**: - `NoTimestamp` removes the need for `created_at` and `updated_at` fields. - `FormatDate` formats the date following a convention. **FormatDate** The convention is: - Ends with `_at` => DateTime - Ends with `_on` => Date You can change the format you use in your UI with two getters. ```js class MyModel extends Model { static get formatDate () { return 'DD.MM.YYYY' } static get formatDateTime () { return 'DD.MM.YYYY HH:mm' } } ``` You can also directly change default values inside the Trait since it is a user Trait and not defined in the core.
If this is merged, I'll provide the same PR to the `API` blueprint. --- app/Middleware/ConvertEmptyStringsToNull.js | 17 +++++++++++++++++ app/Models/Traits/NoTimestamp.js | 15 +++++++++++++++ start/kernel.js | 3 ++- 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 app/Middleware/ConvertEmptyStringsToNull.js create mode 100644 app/Models/Traits/NoTimestamp.js diff --git a/app/Middleware/ConvertEmptyStringsToNull.js b/app/Middleware/ConvertEmptyStringsToNull.js new file mode 100644 index 0000000..a5750cc --- /dev/null +++ b/app/Middleware/ConvertEmptyStringsToNull.js @@ -0,0 +1,17 @@ +'use strict' + +class ConvertEmptyStringsToNull { + async handle ({ request }, next) { + if (Object.keys(request.body).length) { + request.body = Object.assign( + ...Object.keys(request.body).map(key => ({ + [key]: request.body[key] !== '' ? request.body[key] : null + })) + ) + } + + await next() + } +} + +module.exports = ConvertEmptyStringsToNull diff --git a/app/Models/Traits/NoTimestamp.js b/app/Models/Traits/NoTimestamp.js new file mode 100644 index 0000000..45f210e --- /dev/null +++ b/app/Models/Traits/NoTimestamp.js @@ -0,0 +1,15 @@ +'use strict' + +class NoTimestamp { + register (Model) { + Object.defineProperties(Model, 'createdAtColumn', { + get () { return null } + }) + + Object.defineProperties(Model, 'updatedAtColumn', { + get () { return null } + }) + } +} + +module.exports = NoTimestamp diff --git a/start/kernel.js b/start/kernel.js index cba76b4..b4f2720 100644 --- a/start/kernel.js +++ b/start/kernel.js @@ -16,7 +16,8 @@ const globalMiddleware = [ 'Adonis/Middleware/BodyParser', 'Adonis/Middleware/Session', 'Adonis/Middleware/Shield', - 'Adonis/Middleware/AuthInit' + 'Adonis/Middleware/AuthInit', + 'App/Middleware/ConvertEmptyStringsToNull', ] /*