fixed issue with redis models

This commit is contained in:
2024-08-06 13:11:55 -04:00
parent e38504457c
commit 84db245f4a
20 changed files with 558 additions and 323 deletions
+35 -11
View File
@@ -47,17 +47,17 @@ class Table{
}catch(error){
throw error;
}
}
static async exists(index){
try{
await this.get(data);
return true;
}catch(error){
return false;
if(typeof index === 'object'){
index = index[this._key];
}
return await client.SISMEMBER(
redisPrefix(this.prototype.constructor.name),
index
);
}
static async list(){
@@ -86,6 +86,7 @@ class Table{
static async create(data){
// Add a entry to this redis table.
try{
// Validate the passed data by the keyMap schema.
data = objValidate.processKeys(this._keyMap, data);
@@ -94,6 +95,10 @@ class Table{
let error = new Error('EntryNameUsed');
error.name = 'EntryNameUsed';
error.message = `${this.prototype.constructor.name}:${data[this._key]} already exists`;
error.keys = [{
key: this._key,
message: `${this.prototype.constructor.name}:${data[this._key]} already exists`
}]
error.status = 409;
throw error;
@@ -107,7 +112,7 @@ class Table{
// Add the values for this entry.
for(let key of Object.keys(data)){
if(!data[key]) continue;
if(data[key] === undefined) continue;
await client.HSET(
redisPrefix(`${this.prototype.constructor.name}_${data[this._key]}`),
key,
@@ -125,9 +130,26 @@ class Table{
async update(data, key){
// Update an existing entry.
try{
// Validate the passed data, ignoring required fields.
data = objValidate.processKeys(this.constructor._keyMap, data, true);
// Check to see if entry name changed.
if(data[this.constructor._key] && data[this.constructor._key] !== this[this.constructor._key]){
// Remove the index key from the tables members list.
if(data[this.constructor._key] && await this.constructor.exists(data)){
let error = new Error('EntryNameUsed');
error.name = 'EntryNameUsed';
error.message = `${this.constructor.name}:${data[this.constructor._key]} already exists`;
error.keys = [{
key: this.constructor._key,
message: `${this.constructor.name}:${data[this.constructor._key]} already exists`
}]
error.status = 409;
throw error;
}
await client.SREM(
redisPrefix(this.constructor.name),
this[this.constructor._key]
@@ -139,12 +161,14 @@ class Table{
data[this.constructor._key]
);
await client.RENAME(
redisPrefix(`${this.constructor.name}_${this[this.constructor._key]}`),
redisPrefix(`${this.constructor.name}_${data[this.constructor._key]}`),
);
}
// Update what ever fields that where passed.
// Validate the passed data, ignoring required fields.
data = objValidate.processKeys(this.constructor._keyMap, data, true);
// Loop over the data fields and apply them to redis
for(let key of Object.keys(data)){
this[key] = data[key];