sequelize-helpers.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { Sequelize } from 'sequelize'
  2. function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
  3. if (!model.createdAt || !model.updatedAt) {
  4. throw new Error('Miss createdAt & updatedAt attributes to model')
  5. }
  6. const now = Date.now()
  7. const createdAtTime = model.createdAt.getTime()
  8. const updatedAtTime = model.updatedAt.getTime()
  9. return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
  10. }
  11. function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
  12. if (nullable && (value === null || value === undefined)) return
  13. if (validator(value) === false) {
  14. throw new Error(`"${value}" is not a valid ${fieldName}.`)
  15. }
  16. }
  17. function buildTrigramSearchIndex (indexName: string, attribute: string) {
  18. return {
  19. name: indexName,
  20. // FIXME: gin_trgm_ops is not taken into account in Sequelize 6, so adding it ourselves in the literal function
  21. fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + ')) gin_trgm_ops') as any ],
  22. using: 'gin',
  23. operator: 'gin_trgm_ops'
  24. }
  25. }
  26. // ---------------------------------------------------------------------------
  27. export {
  28. throwIfNotValid,
  29. buildTrigramSearchIndex,
  30. isOutdated
  31. }