Skip to content

Commit

Permalink
add caching
Browse files Browse the repository at this point in the history
  • Loading branch information
picklejason committed Dec 18, 2022
1 parent df1df58 commit 77ac0f4
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 7 deletions.
26 changes: 19 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ const path = require("path");
const express = require("express");
const app = express();
const fetch = require("node-fetch");
const NodeCache = require("node-cache");
const myCache = new NodeCache();
const { check, validationResult } = require("express-validator");
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
Expand Down Expand Up @@ -41,7 +43,7 @@ app.get("/", async (req, res) => {

app.get("/create", async (req, res) => {
try {
pokemons = await getAllPokemons();
let pokemons = await getAllPokemons();
res.render("create", { pokemons });
} catch (err) {
console.error(err);
Expand Down Expand Up @@ -163,19 +165,29 @@ app.get("/archive", async (req, res) => {

async function fetchPokemon(pokemon) {
try {
const res = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon}`);
const data = await res.json();
return data;
if (myCache.has(pokemon)) {
return myCache.get(pokemon);
} else {
const res = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon}`);
const data = await res.json();
myCache.set(pokemon, data, 3600);
return data;
}
} catch (err) {
console.log(err);
}
}

async function getAllPokemons() {
try {
const res = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=898`);
const data = await res.json();
return data;
if (myCache.has("allPokemons")) {
return myCache.get("allPokemons");
} else {
const res = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=898`);
const data = await res.json();
myCache.set("allPokemons", data, 3600);
return data;
}
} catch (err) {
console.log(err);
}
Expand Down
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"express": "^4.18.2",
"express-validator": "^6.14.2",
"mongodb": "^4.12.1",
"node-cache": "^5.1.2",
"node-fetch": "^2.0.0"
},
"devDependencies": {
Expand Down

0 comments on commit 77ac0f4

Please sign in to comment.