如何使用 ‘apicache’ 包清除特定路由的缓存。

huangapple go评论78阅读模式
英文:

How to clear cache for a route with the 'apicache' package

问题

以下是您提供的代码的中文翻译:

我正在为我的MERN应用程序使用NPM安装API缓存我希望我的其中一个请求被缓存然后当对另一个路由发出请求时它会刷新缓存获取新数据)。我已经成功使其中一个请求被缓存但我无法清除它

这是我的代码

```javascript
const apicache = require("apicache");

let cache = apicache.middleware;

app.get("/api/users/checkJWT", cache("2 minutes"), async (req, res) => {
  const token = req.headers.authorization?.split(" ")[1];

  const decoded = jwt.verify(token, SECRET_KEY);

  if (decoded != null && (await User.findById(decoded.id)) != null) {
    return res.status(200).json({ valid: true, user: await User.findById(decoded.id) });
  } else {
    return res.status(400).json({ valid: false });
  }
});

app.patch("/api/users/user", authenticateJWTUser, async (req, res) => {
  apicache.clear('/api/users/checkJWT');
  const user = await User.findOne({ name: req.body.username });
  if (req.body.name != null) {
    user.name = req.body.name;
  }
  if (req.body.email != null) {
    user.email = req.body.email;
  }
  if (req.body.password != null) {
    user.password = await bcrypt.hash(req.body.password, 10);
  }
  if (req.body.tasks != null) {
    user.tasks = req.body.tasks;
  }
  try {
    const updatedUser = await user.save();
    res.json(updatedUser);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

我的Git仓库链接: https://github.com/JesseOgunlaja/Task-Tracker-MERN/tree/ae1b0027bfa40f90ab7a3d6208c05a9eb41a4478


请注意,我只提供了代码的翻译部分,没有包含其他内容。

<details>
<summary>英文:</summary>

I&#39;m using NPM install API cache for my MERN application. I want one of my requests to be cached and then when a request is made to another route it refreshes the cache (it fetches the new data). I&#39;ve managed to get one of my requests to be cached but I can&#39;t manage to clear it.


This is my code

const apicache = require("apicache")

let cache = apicache.middleware

app.get("/api/users/checkJWT",cache("2 minutes"), async (req,res) => {
const token = req.headers.authorization?.split(" ")[1]

const decoded = jwt.verify(token,SECRET_KEY)

if(decoded != null && await User.findById(decoded.id) != null) {
return res.status(200).json({valid: true, user: await User.findById(decoded.id)})
}
else {
return res.status(400).json({valid: false})
}
})

app.patch("/api/users/user",authenticateJWTUser, async (req, res) => {
apicache.clear('/api/users/checkJWT')
const user = await User.findOne({ name: req.body.username });
if (req.body.name != null) {
user.name = req.body.name;
}
if (req.body.email != null) {
user.email = req.body.email;
}
if (req.body.password != null) {
user.password = await bcrypt.hash(req.body.password, 10);
}
if (req.body.tasks != null) {
user.tasks = req.body.tasks;
}
try {
const updatedUser = await user.save();
res.json(updatedUser);
} catch (error) {
res.status(400).json({ message: error.message });
}
});


Link to my Git repo: https://github.com/JesseOgunlaja/Task-Tracker-MERN/tree/ae1b0027bfa40f90ab7a3d6208c05a9eb41a4478


</details>


# 答案1
**得分**: 0

I was able to get this work using the [apicache-plus package](https://www.npmjs.com/package/apicache-plus?activeTab=readme). 

```javascript
const apicache = require("apicache-plus");

router.get(
  "/api/users/getName/1",
  apicache.middleware("10 minutes"),
  async (req, res, next) => {
    req.apicacheGroup = "toClear";
    const someData = { someName: "Amy" };
    res.json(someData);
  }
);

router.get("/api/users/user/1/2", async (req, res, next) => {
  console.log("something");
  apicache.clear("toClear");

  const user = { name: "Jeff" };
  res.json(user);
});

(Note: Code parts are not translated.)

英文:

I was able to get this work using the apicache-plus package.

const apicache = require(&quot;apicache-plus&quot;);

router.get(
  &quot;/api/users/getName/1&quot;,
  apicache.middleware(&quot;10 minutes&quot;),
  async (req, res, next) =&gt; {
    req.apicacheGroup = &quot;toClear&quot;;
    const someData = { someName: &quot;Amy&quot; };
    res.json(someData);
  }
);

router.get(&quot;/api/users/user/1/2&quot;, async (req, res, next) =&gt; {
  console.log(&quot;something&quot;);
  apicache.clear(&quot;toClear&quot;);

  const user = { name: &quot;Jeff&quot; };
  res.json(user);
});

huangapple
  • 本文由 发表于 2023年6月2日 01:16:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76384267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定