简体   繁体   中英

Trying to make my functions be able to have dynamic selectors so i dont have to repeat myself

Heres my code, and I find myself having to do this ALOT for parsing json, or making functions.

// Adder Functions... hate repeating myself
async function addPetImagesToPet(petId, fileName) {
  const pet = await db.Pet.findById(petId);
  await pet.petImages.push({'fileName':fileName});
  pet.updated = Date.now();
  await pet.save();
  //console.log(pet);
}

async function addPropertyImagesToProperty(propertyId, fileName) {
  const property = await db.Property.findById(propertyId);
  await property.propertyImages.push({'fileName':fileName});
  property.updated = Date.now();
  await property.save();
  //console.log(property);
}

async function addAccountImagesToAccount(accountId, fileName) {
  const account = await db.Account.findById(accountId);
  await account.accountImages.push({'fileName':fileName});
  account.updated = Date.now();
  await account.save();
  //console.log(account);
}

//how can I do `await db.${my_type/Object_Name!!! <--this is what im asking about}.findById(this obviously can be a var np)

I find myself doing this repeat alot for most of my services, im trying to expand this further for most of my services front end and back end. if i figured out how to do this I could literally have one "CRUD" service for a majority of my use cases for each object type.

Comes alot and has been driving me crazy for parsing JSON objects, making the selector on the object be dynamic...

I use ${} because thats how I dynamically build strings, but cant do it or make it work for functions, or naming, I cant for instance make a string variable and use that name as a name for function, or its methods, but thats exactly what I want to do. Thank you again for anyone able to help.

Thanks in advance.

You could do something like there where you create a hashMap with the individual values.

const hashMap = {
  'pet': {
    dbName:"Pet",
    key: 'petImages'
  },
  'account': {
    dbName: "Account",
    key: 'accountImages'
  },
  'property':{
    dbName: "Property",
    key: 'propertyImages'
  }
}

async function addImagesToAccount(accountId, fileName, type) { // type will be the key for the object above.
  const {dbName, key} = hashMap[type];
  const account = await db[dbName].findById(accountId);
  await account[key].push({'fileName':fileName});
  account.updated = Date.now();
  await account.save();
}

You could use something like this:

async function addImages(type, id, fileName) {
  const entity = await db[type].findById(id);

  entity.updated = Date.now();

  const attribute = `${type.toLowerCase()}Images`;
  entity[attribute].push({ fileName })

  await entity.save();
}

async function main() {
  await addImages('Property', 2, 'text-02');
  await addImages('Account', 3, 'text-03');
  await addImages('Pet', 3, 'text-03');
}

Also I think like the Factory Pattern could help you to code something reusable:).

Ideally, if you wanna use more variables, it is to use and array maybe. It's like a good practice to keep a functions with no more than three variables. But that's a personal perference.

Well i would use a single line to do that, no need to wrap it in a function

await db.Pet.updateOne({ _id: petId }, { $push: : { petImages : {'fileName':fileName}}, updated: Date.now() });

Thank you everyone for the comments and help.

My final code looks like this, sure I could get it shorter.

async function addImagesToObject(objId, objType, fileName) {
  const entity = await db[`${objType}`].findById(objId);
  const attribute = `${objType.toLowerCase()}Images`; //<-- defining selector
  await entity[attribute].push({'fileName':fileName});
  entity.updated = Date.now();
  await entity.save();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM