'Adonis js how to mutate value when saving on model

Using Adonis js

When saving , im trying to mutate a ISO string to Datetime (reverse of serailizing DateTime fields to ISO string). Cant find a way to do this in model, like i would as a mutator in laravel. When I attempt to use beforeSave() hook to achieve this I get a type error because model is expecting DateTime not string type. Any ideas?

Controller

public async update({ request, params, response }) {
    let data = request.all()

    //Hopefully move this logic to model for date fields
    for (const [key, value] of Object.entries(data)) {
        if (['recievedAt', 'dueAt'].includes(key) && typeof value == 'string') {
            data[key] = DateTime.fromISO(value)
        }
    }

    const task = await Task.findOrFail(params.id)
    task.merge(data)
    await task.save()

    return response.status(200).send({ request, params: params.id, data })
}

Model

@column.dateTime({
    serialize: (value: DateTime | null) => {
        return value ? value.setZone('utc').toISODate() : value
    },
})
public recievedAt: DateTime


Solution 1:[1]

You shouldn't need to anything if you use column.date or column.datetime.

The decorator self defines the prepare, consume and the serialize methods to ensure

  • You are constantly working with an instance of luxon.DateTime in your codebase.
  • The date is serialized as an ISO date.
  • The date is formatted correctly as per the underlying database driver.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Berkan