3.1.10 • Published 9 months ago

base-repo v3.1.10

Weekly downloads
66
License
UNLICENSED
Repository
github
Last release
9 months ago

Description

Cache Invalidation at model level extended features for sequelize-typescript (v2.1.0 or later)

Installation

$ npm install base-repo sequelize@^6.x.x sequelize-typescript@^2.x.x

Your tsconfig.json needs the following flags:

"target": "es6", // or a more recent ecmascript version
"experimentalDecorators": true,
"emitDecoratorMetadata": true

Module Definition

make sure defined all model of sequelize at this level and

@Module({
  ...
  imports: [
    RedisModule.register(cacheConfig() as RedisModuleOptions),

    SequelizeCacheModule.register({
      defaultTTL: 5, // DEFINE TTL FOR ALL PROJECT seconds
      // DEFINE HOW TO GET CACHE FROM GIVEN KEY
      callbackGet: async ({ key }) => CacheConfigModule.store.get(key),
      // DEFINE HOW TO INVALIDATE CACHE FROM GIVEN KEY
      callbackInvalidate: ({ key }) => (CacheConfigModule?.store?.del?.(key) || null),
      // DEFINE HOW TO SET CACHE FROM GIVEN KEY VALUE AND TTL
      callbackSet: async ({ key, value, ttl }) => CacheConfigModule.store.set(key, value, { ttl }),
      callbackGetKey: async ({ keyPattern }) => CacheConfigModule.store.keys?.(`${process.env.CACHE_PREFIX}${keyPattern}`) || [],
    }),

    SequelizeModule.forRoot({
      ...DBOptions,
    }),
   ...
  ],
})

export class CacheConfigModule {
  static store: Store;

  constructor(@Inject(CACHE_MANAGER) private store: Store) {
    CacheConfigModule.store = this.store;
  }
}

Model Definition

@Cache(options)

the @Cache is used for defined ttl and cache for findOne and automatically invalidate findOneCache/findByPkCache

@Cache API Options

OptionsDescription
options.ttlset TTL for this model, this will override ttl at module (Optional)
@Cache({
  ttl: 100,
})
@Table()
export class DmCourse extends BaseModel {}

Extend BaseModel

@Cache({
  ttl: 100,
})
@Table()
export class DmCourse extends BaseModel {
  // default `{modelName} data not found'
  static notFoundMessage = 'your model not found message';

  /**
   *  @default `updatedAt`
   * @description `this is for checking newest updated timestamp for cached list.`
  */
  static onUpdateAttribute = 'modifiedAt'

   @UpdatedAt
  @Column({ field: 'UpdatedAt' })
    modifiedAt: Date;
}

the Model need to extends BaseModel

More Strict

interface DmCourseAtt {
  id: number
  name: string;
  type: number;
}

interface DmCreateAtt extends DmCourseAtt Omit<DmCourseAtt, 'id'>

@Cache({
  ttl: 100,
})
@Table()
export class DmCourse extends BaseModel<DmCourseAtt, DmCreateAtt> {}

for strict type that can used at default function from sequelize-typescript can be planted at generic type 2 and 3 sequelize-typescript strict

How to use

Model.findOneCache(cacheOptions)

  • cacheOptions : FindOptions limited findOptions from sequelize-typescript
// file: DmCourse.ts

@Cache() //default ttl module
@Table()
export class DmCourse extends BaseModel<DmCourseAtt, DmCreateAtt> {}

...

// file: Course.controller.ts

class CourseController {
  async getCourse() {
    const course = await DmCourse.findOneCache({
      where: {
        isDeleted: false,
        name: 'Math',
      },
      rejectOnEmpty: true, // use model default throw, or use use throw Exception
      // rejectOnEmpty: new BadRequestException('message')
    })
  }
}
  • you have to use All defined cache attributes that has name byIsDeletedAndName
  • every query that outside of defined cache will not executed

findOneCache API Options

OptionsDescription
cacheOptionssome function from Sequelize FindOptions
cacheOptions.ttlset TTL for this cache key, this will override ttl at module and model (Optional), (Required) when has include Query
cacheOptions.rejectOnEmptywill throw error when set true (Optional)

Model.findByPkCache(id, options)

class CourseController {
  async getCourse() {
    const course = await DmCourse.findByPkCache(1, {
      ttl: 100,
    });
  }
}
  • find By Primary Cache will invalidate when any destroy or update

findByPkCache API Options

OptionsDescription
idvalue of id
cacheOptionssome function from Sequelize FindOptions
cacheOptions.ttlset TTL for this cache key, this will override ttl at module and model (Optional), (Required) when has include Query
cacheOptions.rejectOnEmptywill throw error when set true (Optional)

Model.findAllCache(cacheOptions)

class CourseController {
  async getCourse() {
    const course = await DmCourse.findAllCache({
     ttl: 100,
     attributes: ['id','name','type']
     where: {
       isDeleted: false,
     },
     order: [
       ['id','desc']
     ],
     include: [
       {
         // any association
       }
     ],
     limit: 10,
    })
  }
}
  • find all data and Cache it when has value. will invalidate and update cache when ttl reach 0 or when get max updates or count is different from before

findAllCache API Options

OptionsDescription
cacheOptions.ttlset TTL for this cache key, this will override ttl at module and model (Optional), (Required) when has include Query
{...cacheOptions}is same with FindOptions from sequelize-typescript

Stay in touch

3.1.10

9 months ago

3.1.9

9 months ago

3.1.5-beta.0

1 year ago

3.1.5-beta.1

1 year ago

3.1.5-rc2.0

1 year ago

3.1.5-beta.2

1 year ago

3.1.8

1 year ago

3.1.7-rc.0

1 year ago

3.1.7-rc.1

1 year ago

3.1.7

1 year ago

3.1.6

1 year ago

3.1.5

1 year ago

3.1.4

1 year ago

2.2.4-0

1 year ago

2.3.2

2 years ago

2.3.1

2 years ago

2.3.3

2 years ago

3.1.3

2 years ago

3.1.2

2 years ago

3.1.1

2 years ago

3.0.4

2 years ago

3.0.3

2 years ago

3.0.2

2 years ago

3.0.1

2 years ago

2.3.0

2 years ago

3.1.0

2 years ago

2.2.3

2 years ago

2.2.2

2 years ago

2.2.1

3 years ago

2.2.0

3 years ago

2.1.12

3 years ago

2.1.13

3 years ago

2.1.11

3 years ago

2.1.9

3 years ago

2.1.10

3 years ago

2.1.8

3 years ago

2.1.2

3 years ago

2.1.1

3 years ago

2.1.4

3 years ago

2.1.3

3 years ago

2.1.6

3 years ago

2.1.5

3 years ago

2.1.7

3 years ago

2.1.0

3 years ago

2.0.9

3 years ago

2.0.8

3 years ago

2.0.10

3 years ago

2.0.3

3 years ago

2.0.5

3 years ago

2.0.4

3 years ago

2.0.7

3 years ago

2.0.6

3 years ago

2.0.0-beta.6

3 years ago

2.0.0-beta.5

3 years ago

2.0.2

3 years ago

2.0.0-beta.2

3 years ago

2.0.0-beta.1

3 years ago

2.0.0-beta.0

3 years ago

2.0.0-beta.4

3 years ago

2.0.1

3 years ago

1.3.11

3 years ago

1.3.10

3 years ago

1.3.8

3 years ago

1.3.7

3 years ago

1.3.6

3 years ago

1.3.5

3 years ago

2.0.0

3 years ago

1.3.4

3 years ago

1.3.3

3 years ago

1.3.2

3 years ago

1.3.1

3 years ago

1.3.0

4 years ago

1.2.15

4 years ago

1.2.14

4 years ago

1.2.13

4 years ago

1.2.11

4 years ago

1.2.9

4 years ago

1.2.10

4 years ago

1.2.8

4 years ago

1.2.7

4 years ago

1.2.6

4 years ago

1.2.0

4 years ago

1.1.0

4 years ago

1.2.4

4 years ago

1.2.3

4 years ago

1.2.2

4 years ago

1.2.1

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago