How to 'nullify' empty request fields?

Hi.
I have a User Model. When you create the user there are some not required fields, as age and gender.

UserController.js

async store ({request, ...}){

const {....,age, gender} = request.all()

newUser = await User.create({
...
age:age,
gender:gender
})
...
}

With this if age or gender are empty (age:"") the value stored on db is “” and not NULL as ‘supposed’ to be.

The solution that will work is to check each not required field one by one and to include them only if they are not “”. Not very pretty I think.

Anyone has a better solution to this?

B/R.

1 Like

You could leverage on Sanitizers, Hooks etc.

For Sanitizers:
I’ll start by creating a custom sanitizer which I’ll call stringify.
So in your hooks.js file, you declare:

const { ioc } = require("@adonisjs/fold");

hooks.after.providersRegistered(() => {
    const { sanitizor } = ioc.use("Validator");

    sanitizor.stringify = val => (val == null) ? "" : val;
});

There are also in-built sanitizers such as to_int, etc., for adonis, see Sanitizers.

Then create a validation rule by running adonis make:validator <name_of_validator>.

In app/Validators/<name_of_validator>.js, add the sanitization rules to sanitization portion:

get sanitizationRules() {
    return {
      gender: "stringify" // doing so will either make this field "" or its original value.
    };
}

@jorgeyoma Hi!

In the case these properties don’t exist on request body, you can give a default value to them like this :

const { ..., age = null, gender = null } = request.all()

Otherwise, use Setters, Hooks (depending on how you would implement it, i.e : synchronously or asynchronously) or add a custom sanitizer and use it when you validate data.

1 Like

You could also implement nullable() on the columns at the migration level.

table.string('gender').nullable()

I think that would reduce the need for additional code