agrs-sequelize-sdk 1.1.18 → 1.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -63,21 +63,49 @@ module.exports = (sequelize, DataTypes) => {
63
63
  ],
64
64
  hooks: {
65
65
  beforeCreate: async (record, options) => {
66
- const existingKeyword =
67
- await sequelize.models.KeywordPerformance.findOne({
68
- where: {
69
- Keyword: sequelize.where(
70
- sequelize.fn("LOWER", sequelize.col("Keyword")),
71
- sequelize.fn("LOWER", record.Keyword)
72
- ),
73
- },
74
- order: [["Date", "ASC"]],
75
- attributes: ["FirstAppearanceDate"],
76
- transaction: options.transaction,
77
- });
66
+ try {
67
+ // Find the earliest date for this keyword using raw query for better performance
68
+ const [result] = await sequelize.query(
69
+ `
70
+ SELECT MIN("Date") as first_date
71
+ FROM "KeywordPerformance"
72
+ WHERE LOWER("Keyword") = LOWER(:keyword)
73
+ `,
74
+ {
75
+ replacements: { keyword: record.Keyword },
76
+ type: sequelize.QueryTypes.SELECT,
77
+ transaction: options.transaction,
78
+ }
79
+ );
78
80
 
79
- record.FirstAppearanceDate =
80
- existingKeyword?.FirstAppearanceDate || record.Date;
81
+ // If no existing record found, use current record's date
82
+ // Otherwise, use the earlier date between existing and current
83
+ const existingFirstDate = result?.first_date;
84
+ record.FirstAppearanceDate = existingFirstDate
85
+ ? Math.min(new Date(existingFirstDate), new Date(record.Date))
86
+ : record.Date;
87
+
88
+ // If we found an earlier date, update all existing records for this keyword
89
+ if (existingFirstDate && record.Date < existingFirstDate) {
90
+ await sequelize.query(
91
+ `
92
+ UPDATE "KeywordPerformance"
93
+ SET "FirstAppearanceDate" = :newDate
94
+ WHERE LOWER("Keyword") = LOWER(:keyword)
95
+ `,
96
+ {
97
+ replacements: {
98
+ newDate: record.Date,
99
+ keyword: record.Keyword,
100
+ },
101
+ transaction: options.transaction,
102
+ }
103
+ );
104
+ }
105
+ } catch (error) {
106
+ console.error("Error in FirstAppearanceDate hook:", error);
107
+ throw error;
108
+ }
81
109
  },
82
110
  },
83
111
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agrs-sequelize-sdk",
3
- "version": "1.1.18",
3
+ "version": "1.1.19",
4
4
  "main": "index.js",
5
5
  "scripts": {
6
6
  "start": "node index.js",