Caching in Node.js using Memcached
Tags: node, javascript, beginners, webdev
Published: 2021-07-28 00:00:08

I've already written articles about caching using [Redis](https://dev.to/franciscomendes10866/caching-in-node-js-using-redis-2o80) and also explained how we can cache our Api using [node-cache](https://dev.to/franciscomendes10866/simple-in-memory-cache-in-node-js-gl4). 

In each of these articles, I've provided little background on using each of them, and in my opinion, [Memcached](https://github.com/memcachier/memjs) is something I should have added to the list.

One of the great advantages of using Memcached in your applications is stability and performance, not to mention that the system resources it consumes and the space it takes up is minimal.

As with the examples in the articles mentioned above, I'll do something similar today, which is simple but can be easily replicated in your projects.

# Let's code

In today's example I'm going to use my favorite framework, but the client we're going to use is agnostic, that is, the code that is present in this article can be reused for other frameworks.

The framework we are going to use today is [tinyhttp](https://github.com/tinyhttp/tinyhttp) which is very similar to Express. The reason for its use to me is pretty obvious, but I recommend visiting the github repository.

In addition, we will still install [milliparsec](https://github.com/tinyhttp/milliparsec), which is a super lightweight body parser, and the Memcached client we will be using will be [memjs](https://github.com/memcachier/memjs).

But today's topic isn't about frameworks, so let's start by installing the following dependencies:

```sh
npm i @tinyhttp/app @tinyhttp/logger milliparsec memjs
```

First we will import our tinnyhttp dependencies and we will register the respective middlewares:

```js
import { App } from "@tinyhttp/app";
import { logger } from "@tinyhttp/logger";
import { json } from "milliparsec";

const app = new App();

app.use(logger());
app.use(json());

// More stuff comes here.

app.listen(3333);
```
Now we can create our route, which will only hold one parameter, which in this case will be the `id`:

```js
app.post("/:id", (req, res) => {
  // Logic goes here.
});
```

First, let's get the id value of the parameters. Next, we will create an object, in which we will have a property with the value of the id and the remaining properties will be all those coming from the http request body.

```js
app.post("/:id", (req, res) => {
  const { id } = req.params;
  const data = { id, ...req.body };
  // More logic goes here.
});
```

Then we will return a response, which will have `status code 201` (to indicate that the data was added to Memcached) and the respective object that was created by us.

```js
app.post("/:id", (req, res) => {
  const { id } = req.params;
  const data = { id, ...req.body };
  return res.status(201).json(data);
});
```

However, we can't add anything to Memcached yet because it still needs to be configured. So we can already create our client. Like this:

```js
import { App } from "@tinyhttp/app";
import { logger } from "@tinyhttp/logger";
import { json } from "milliparsec";
import { Client } from "memjs";

const app = new App();
const memcached = Client.create();

// Hidden for simplicity
```

Now we can go back to our route and add Memcached, for that we'll use the `.set()` method to input some data. 

In this method we will pass three arguments, the first one will be our `key`, which in this case is the **id**. 

The second argument will be the `value` of that same key, which we must convert to a string. 

The third will be the time you want to persist that same data, in **seconds**.

In addition to this we will have to make our function asynchronous because the `.set()` method returns a Promise.

```js
app.post("/:id", async (req, res) => {
  const { id } = req.params;
  const data = { id, ...req.body };
  await memcached.set(id, JSON.stringify(data), { expires: 12 });
  return res.status(201).json(data);
});
```

The next time you access the route, it will persist in Memcached, but we're not there yet. 

That's because we still have to create a middleware that checks if there is a key with id equal to what we are passing in the parameters.

If there is a key equal to the id we passed in the parameters, we'll want to return the value of that key so we don't have to access our controller. If it doesn't exist, we go to our controller to create a new key.

If you're confused, relax because it will soon make sense. In this case, let's create a middleware called **verifyCache**:

```js
const verifyCache = (req, res, next) => {
  // Logic goes here.
};
```

First let's get the id value that is passed in the parameters.

```js
const verifyCache = (req, res, next) => {
  const { id } = req.params;
  // More logic goes here.
};
```

Next, we'll use the Memcached client's `.get()` method. Let's pass two arguments in this method, the first argument will be the `id`. The second argument will be a `callback` and will also have two arguments. The first will be the `error`, the second will be the key `value`.

```js
const verifyCache = (req, res, next) => {
  const { id } = req.params;
  memcached.get(id, (err, val) => {
    // Even more logic goes here.
  });
};
```

If an error occurs, we have to handle it as follows:

```js
const verifyCache = (req, res, next) => {
  const { id } = req.params;
  memcached.get(id, (err, val) => {
    if (err) throw err;
    // Even more logic goes here.
  });
};
```

Now, see that the key value is non-null, we want to return its value, for that we will send a response with `status code 200` (to show that it was obtained from Memcached successfully) and we will send our json object (but first it must be converted from string to json).

If the key value is null, we will proceed to the controller.

```js
const verifyCache = (req, res, next) => {
  const { id } = req.params;
  memcached.get(id, (err, val) => {
    if (err) throw err;
    if (val !== null) {
      return res.status(200).json(JSON.parse(val));
    } else {
      return next();
    }
  });
};
```

Now with the created middleware we just add it to our route:

```js
app.post("/:id", verifyCache, async (req, res) => {
  const { id } = req.params;
  const data = { id, ...req.body };
  await memcached.set(id, JSON.stringify(data), { expires: 12 });
  return res.status(201).json(data);
});
```

Your final code should look like the following:

```js
import { App } from "@tinyhttp/app";
import { logger } from "@tinyhttp/logger";
import { json } from "milliparsec";
import { Client } from "memjs";

const app = new App();
const memcached = Client.create();

app.use(logger());
app.use(json());

const verifyCache = (req, res, next) => {
  const { id } = req.params;
  memcached.get(id, (err, val) => {
    if (err) throw err;
    if (val !== null) {
      return res.status(200).json(JSON.parse(val));
    } else {
      return next();
    }
  });
};

app.post("/:id", verifyCache, async (req, res) => {
  const { id } = req.params;
  const data = { id, ...req.body };
  await memcached.set(id, JSON.stringify(data), { expires: 12 });
  return res.status(201).json(data);
});

app.listen(3333);
```

## Conclusion

As always, I hope I was brief in explaining things and that I didn't confuse you. Have a great day! 🙌 🥳