irfanzainudin / pantunis-api

https://pantunis-api.vercel.app
MIT License
2 stars 1 forks source link

"cariGunaKata" Code simplification suggestion for better comprehension and maintenance #3

Open irsyadpage opened 1 month ago

irsyadpage commented 1 month ago

The original handler for /cariGunaKata api is:

https://github.com/irfanzainudin/pantunis-api/blob/73aff3f6c9e9ac19c475b1d9f91d3a146eb96144/api/cariGunaKata.js#L8-L92

Possible improvements:

let query = knex("pantun")
    .join("sumber", "pantun.sumber", "=", "sumber.id");

if (req.query.kata.length === 0) {
  // Return only first 100 pantun if parameter "kata" is empty
  query = query.limit(100);

} else {
  // Append <KATA> to query
  query = query
    .whereLike("bayang1", "%" + req.query.kata + "%")
    .orWhereLike("bayang2", "%" + req.query.kata + "%")
    .orWhereLike("maksud1", "%" + req.query.kata + "%")
    .orWhereLike("maksud2", "%" + req.query.kata + "%");
}

// Add SELECT statement and perform the query
query.select(
    "pantun.id as pantun_id",
    "pantun.bayang1 as pantun_bayang1",
    "pantun.bayang2 as pantun_bayang2",
    "pantun.maksud1 as pantun_maksud1",
    "pantun.maksud2 as pantun_maksud2",
    "pantun.jenis as pantun_jenis",
    "sumber.id as sumber_id",
    "sumber.tajuk as sumber_tajuk",
    "sumber.pengkarya as sumber_pengkarya",
    "sumber.pautan as sumber_pautan"
  )
  .then((response) => {
    // Send the specific extracted pantun from database in response
    res.json(response);
  })
  .catch((err) => {
    // Send a error message in response
    res.json({
      message: `There was an error retrieving the first 100 pantun ${req.query.kata}: ${err}`,
    });
  });
irfanzainudin commented 1 month ago

Thanks so much for opening the issue!

Everything looks great, a slight improvement on the error message would be:

message: `There was an error retrieving pantuns using "${req.query.kata}": ${err}`,

If you want to submit a PR, that'd be great. Otherwise, I can just grab the code and credit you somehow.

irsyadpage commented 1 month ago

My bad, forgot to improve the message.

Created #4 PR with the suggested message.