3

I am using objection.js ORM for my node.js project. Everything is good, I want to trim all the fields before actually saving the data in the PostGres database table. I have also used mongoose in some of the projects, it allows to define {trim: true} in the model.

I am adding a sample model code for the reference:

// @flow

import Model from './Model';
import Transaction from './Transaction';
import dbMap from './dbMap';

export default class ClaimCode extends Model {
    amount: number;
    claimId: number;
    code: string;
    codeDate: Date;
    presentOnAdmission: string;
    throughDate: Date;
    claimCodeTypeId: number;

    static tableName = 'claim_code';
}

dbMap(ClaimCode, {});

Do we have a way to do the same in objection js model?

Dinesh Rawat
  • 970
  • 10
  • 32

1 Answers1

2

I think you should be able to create base model and override $formatDatabaseJson(json) method, which may go through all the string fields and trim them before saving (http://vincit.github.io/objection.js/#_s_formatdatabasejson).

class YourBaseModel extends Model {
    $formatDatabaseJson(json) {
      json = super.$formatDatabaseJson(json);
      // trim here all strings too before returning json...
      return json;
    }
}

If you would like to trim values already when creating models from e.g. data read from HTTP requests, overriding $parseJson() might work better.

Mikael Lepistö
  • 18,909
  • 3
  • 68
  • 70