From 8c4bbd946d2247c2e239cbbf8773d2d31c1a57aa Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 10 Jan 2023 11:09:30 +0100 Subject: Refactor model utils --- server/models/shared/sequelize-helpers.ts | 39 +++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 server/models/shared/sequelize-helpers.ts (limited to 'server/models/shared/sequelize-helpers.ts') diff --git a/server/models/shared/sequelize-helpers.ts b/server/models/shared/sequelize-helpers.ts new file mode 100644 index 000000000..7af8471dc --- /dev/null +++ b/server/models/shared/sequelize-helpers.ts @@ -0,0 +1,39 @@ +import { Sequelize } from 'sequelize' + +function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) { + if (!model.createdAt || !model.updatedAt) { + throw new Error('Miss createdAt & updatedAt attributes to model') + } + + const now = Date.now() + const createdAtTime = model.createdAt.getTime() + const updatedAtTime = model.updatedAt.getTime() + + return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval +} + +function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) { + if (nullable && (value === null || value === undefined)) return + + if (validator(value) === false) { + throw new Error(`"${value}" is not a valid ${fieldName}.`) + } +} + +function buildTrigramSearchIndex (indexName: string, attribute: string) { + return { + name: indexName, + // FIXME: gin_trgm_ops is not taken into account in Sequelize 6, so adding it ourselves in the literal function + fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + ')) gin_trgm_ops') as any ], + using: 'gin', + operator: 'gin_trgm_ops' + } +} + +// --------------------------------------------------------------------------- + +export { + throwIfNotValid, + buildTrigramSearchIndex, + isOutdated +} -- cgit v1.2.3