All files timestamps.js

100% Statements 26/26
100% Branches 24/24
100% Functions 2/2
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63        6x 6x   42x   42x 36x     5x 5x 5x 5x   5x     5x 1x 1x     5x               42x 4x         38x 38x     5x       5x         5x         5x        
export default {
  rxdb: true,
  prototypes: {
    RxDatabase(proto) {
      const prevCollection = proto.collection;
      Object.assign(proto, {
        async collection(model, ...other) {
          const timestamps = model && model.options && model.options.timestamps;
 
          const collection = await prevCollection.call(this, model, other);
          if (!timestamps) return collection;
 
          // Register hooks
          collection.preInsert((data) => {
            const now = new Date().toISOString();
            if (!data.createdAt) data.createdAt = now;
            if (!data.updatedAt) data.updatedAt = now;
 
            return data;
          });
 
          collection.preSave((data, doc) => {
            data.updatedAt = new Date().toISOString();
            return data;
          });
 
          return collection;
        }
      });
    }
  },
  overwritable: {},
  hooks: {
    preCreateRxCollection(model) {
      if (!model.schema || !model.schema.properties) {
        throw Error(
          'RxCollection(s) must have a a "schema" property, with a "properties" key'
        );
      }
 
      const timestamps = model && model.options && model.options.timestamps;
      if (!timestamps) return model;
 
      // Set schema
      model.schema.properties.createdAt = model.schema.properties.createdAt || {
        format: 'date-time',
        type: 'string'
      };
      model.schema.properties.updatedAt = model.schema.properties.updatedAt || {
        format: 'date-time',
        type: 'string'
      };
 
      model.schema.required = (model.schema.required || []).concat([
        'createdAt',
        'updatedAt'
      ]);
 
      return model;
    }
  }
};