I made a website to get data from the D1 Database.
But i am unable to setup cache on server side.
Everytime a user requests the seach, the system has to query it in the database. which is very slow.
I want the worker to store data in cache api.
eg.
example.com/search?name=google
how i can setup cache.
my code looks like this
if (path === "/search") {
var name = await url.searchParams.get("name") || "";
var pageno = await url.searchParams.get("page") || "1";
if (name === "") {
const results = [];
return Response.json(
results, {
status: 200,
headers: {
"content-type": "application/json",
"Access-Control-Allow-Origin": "*",
"Cache-Control": "max-age=86400"
}
}
);
} else {
const nameArray = name.split(" ");
const whereClause = nameArray.map((name2) => `name LIKE '%${name2}%'`).join(" AND ");
const resultsPerPage = 10;
const query = `SELECT * FROM archive_db_data WHERE ${whereClause} LIMIT ${resultsPerPage} OFFSET ${(pageno - 1) * resultsPerPage}`;
const {
results
} = await env.DB.prepare(query).all();
const response = {
results,
page: pageno
};
return Response.json(
response, {
status: 200,
headers: {
"content-type": "application/json",
"Access-Control-Allow-Origin": "*",
"Cache-Control": "max-age=86400"
}
}
);
}
}
I’ve tried this Cache · Cloudflare Workers docs
but couldn’t fix the cache.
the server still queries d1 instead of instant serving.