I’m trying to build a REST API with express, sequelize (PostgreSQL dialect) and node.
Essentially I have two endpoints:
Method | Endpoint | Desc. |
---|---|---|
GET | /api/players |
To get players info, including assets |
POST | /api/assets |
To create an asset |
And there is a mechanism which updates a property (say price) of assets, over a cycle of 30 seconds.
Goal
I want to cache the results of GET /api/players
, but I want some control over it, so that whenever a user creates an asset
(using POST /api/assets
) and right after that a request to GET /api/players
should give the updated data (i.e. including the property which updates for every 30 seconds) and cache it until it gets updated in the next cycle.
Expected
The following should demonstrate it:
-
GET /api/players
JSON Response:
[ { "name": "John Doe" "assets": [ { "id":1 "price": 10 } ] } ]
-
POST /api/assets
JSON Request:
{ "id":2 }
-
GET /api/players
JSON Response:
{ "name": "John Doe" "assets": [ { "id":1 "price": 10 }, { "id":2 "price": 7.99 } ] }
What I have managed to do so far
I have made the routes, but GET /api/players
has no cache mechanism and basically queries the database every time it is requested.
Some solutions I have found, but none seem to meet my scenario
apicache
(https://www.youtube.com/watch?v=ZGymN8aFsv4&t=1360s): But I don’t have a specific duration, because a user can create anasset
anytime.
Example implementation
I have seen (kind off) similar implementation (that I desire) in Github actions workflow for implementing cache, where you define a key and unless the key has changed it uses the same packages and doesn’t install packages everytime, (example: https://github.com/python-discord/quackstack/blob/6792fd5868f28573bb8f9565977df84e7ba50f42/.github/workflows/quackstack.yml#L39-L52)
Is there any package, to do that? So that while processing POST /api/assets
I can change the key in its handler, and thus GET /api/players
gives me the updated result (also I can change the key in that 30 seconds cycle too), and after that it gives me the cached result (until it is updated in the next cycle).
Note: If you have a solution please try to stick with some npm packages, rather than something like redis
, unless its the only/best solution.
Thanks in advance!
(P.S. I’m a beginner and this is my first question in SO)
2
Answers
Typically caching is done with help of Redis. Redis is in-memory key-value store. You could handle the cache in the following manner.
Alternatively, you could use Memcached.
A bit late to this answer but I was looking for a similar solution. I found that the apicache library not only allows for caching for specified durations, but the cache can also be manually cleared.
Here is an example for your implementation: