2

I had taken look hooks provided for lower version but I want to know how can I add timestamp createdAt & updatedAt through models without interacting same for timestamps in controller.

I had worked on Rails but Loopback-4 is something new to me and not as flexible as Rails. I require this timestamps only for few specific models

Irfanullah Jan
  • 3,336
  • 4
  • 24
  • 34
ray
  • 5,454
  • 1
  • 18
  • 40

2 Answers2

3

You can do this in following way:-

In Model File:

@property({
  type: 'date',
  default: () => new Date()
})
created ? : string;

@property({
  type: 'date',
  default: () => new Date()
})
modified ? : string;

In Repository File:

constructor(
  @inject('datasources.db') dataSource: DbDataSource,  
) {
  super(User, dataSource);

  (this.modelClass as any).observe('persist', async (ctx: any) => {
    ctx.data.modified = new Date();
  });
}
Manish Balodia
  • 1,863
  • 2
  • 23
  • 37
0

I'm bumping into this in 2022 and the suggested answer is now relying on legacy code.

The modelClass field is of type PersistedModelClass coming from import legacy from 'loopback-datasource-juggler'; which is backward-compatibility for operation hooks in Loopback v4.

See packages/repository/src/repositories/legacy-juggler-bridge.ts in Github

The current solution is to use mixins as per the following issue/comment on Github: https://github.com/loopbackio/loopback-next/issues/1857#issuecomment-618207056

Hussard
  • 656
  • 7
  • 14