I’ve been trying to build a helper function that will allow me to apply DRY pattern in order to stop repeating myself. My backend and the whole application is complete, however, I’d like to optimize my code, and my actual problem is that pretty much every express http method is similarly formatted the same way. The only time I’ve happened to come close to the solution is when I’ve omitted the req.params as arguments. The problem is that each method has its own req.params format. Here’s how I was trying to solve:
-
I tried to use node-persist package to store req.params, and it only works after I change and resave the file, which makes sense. This happened as I first passed the params as the argument and tried to pass the persisted params value when I call the function. If there’s a way to have the req.params stored somewhere locally first, I wouldn’t be worried.
-
Second Option, I tried to use recursion and called the so-called function twice. I expected the first call to return an undefined params, and the second function call to return stored req.params, but unfortunately it wasn’t the case.
-
I then decided to try using req.redirect where I’ve to access the database with req.params that came from req.query. Although this works, it still brings me back to the same problem as I’ll keep redirecting everything
-
My problem, I want to have a helper function like the following:
export const storage = require('node-persist'); //package to persist data
Few of types used:
type AllHTTPMethods = "post" | "delete" | "all" | "get" | "put" | "patch" | "options" | "head";
type HTTPMethod = core.IRouterMatcher<core.Express, AllHTTPMethods>;
export async function onFetch(httpMethod: HTTPMethod | any, sql: string, path:string, params?: string){
httpMethod(path, async(req, res) => {
await storage.init({});
/**
Check if there is something already stored
*/
if (Object.keys(req.params).length === 0) {
await storage.setItem('params', req.params)
await storage.updateItem('params', req.params)
}
conn.query(sql, [params],
(err:any, data:any) => {
if (err) {
return new Error("Something went wrongn"+err)
}
console.log("Successfully fetched");
console.log(data)
return res.json(data);
})
})
}
Here’s how I invoked them:
//This one works because params aren't involved
async all() {
await onFetch(app.get.bind(app), "select * from products", "/products")
.then(() => console.log("Successfully fetched products"))
.catch(e => console.error(e))
}
//This one didn't work Because the function needs to called first before
//persisting
getProductById = async () => {
await storage.init()
const paramsObj = await storage.getItem("params"); //returns empty object {}
await onFetch(app.post.bind(app), "select * from products where id = ?", "/product/:id", paramsObj.id)
}
And the last trick I tried was to have req.params from client upfront, then redirect them to another router
- Helper function to send req.params:
export function generateParams(
httpMethod: HTTPMethod,
path: string,
params: string,
) {
httpMethod(path, (req, res) => {
const paramsObject = JSON.stringify(req.params);
return res.redirect(`/params/api/?${params}=${paramsObject}`)
})
}
Calling:
generateParams(app.post.bind(app), "/product/:id", "product")
It works but it’s still the same problem I was trying to avoid beforehand
app.get('/params/api', async (req, res)=> {
var product: string | string[] | any | undefined = req.query.product;
var id:any = JSON.parse(product).id
conn.query("select * from products where id = ?", [id], (err, data)=>{
if (err) {
return
}
res.json(data)
})
});
Thanks in advance