query.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { BindOrReplacements, Op, QueryTypes, Sequelize } from 'sequelize'
  2. import validator from 'validator'
  3. import { forceNumber } from '@shared/core-utils'
  4. function doesExist (sequelize: Sequelize, query: string, bind?: BindOrReplacements) {
  5. const options = {
  6. type: QueryTypes.SELECT as QueryTypes.SELECT,
  7. bind,
  8. raw: true
  9. }
  10. return sequelize.query(query, options)
  11. .then(results => results.length === 1)
  12. }
  13. function createSimilarityAttribute (col: string, value: string) {
  14. return Sequelize.fn(
  15. 'similarity',
  16. searchTrigramNormalizeCol(col),
  17. searchTrigramNormalizeValue(value)
  18. )
  19. }
  20. function buildWhereIdOrUUID (id: number | string) {
  21. return validator.isInt('' + id) ? { id } : { uuid: id }
  22. }
  23. function parseAggregateResult (result: any) {
  24. if (!result) return 0
  25. const total = forceNumber(result)
  26. if (isNaN(total)) return 0
  27. return total
  28. }
  29. function parseRowCountResult (result: any) {
  30. if (result.length !== 0) return result[0].total
  31. return 0
  32. }
  33. function createSafeIn (sequelize: Sequelize, toEscape: (string | number)[], additionalUnescaped: string[] = []) {
  34. return toEscape.map(t => {
  35. return t === null
  36. ? null
  37. : sequelize.escape('' + t)
  38. }).concat(additionalUnescaped).join(', ')
  39. }
  40. function searchAttribute (sourceField?: string, targetField?: string) {
  41. if (!sourceField) return {}
  42. return {
  43. [targetField]: {
  44. // FIXME: ts error
  45. [Op.iLike as any]: `%${sourceField}%`
  46. }
  47. }
  48. }
  49. export {
  50. doesExist,
  51. createSimilarityAttribute,
  52. buildWhereIdOrUUID,
  53. parseAggregateResult,
  54. parseRowCountResult,
  55. createSafeIn,
  56. searchAttribute
  57. }
  58. // ---------------------------------------------------------------------------
  59. function searchTrigramNormalizeValue (value: string) {
  60. return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
  61. }
  62. function searchTrigramNormalizeCol (col: string) {
  63. return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
  64. }