Skip to content

Express middleware to avoid duplicates requests made by client

License

Notifications You must be signed in to change notification settings

romch007/duplicate-requests

Repository files navigation

duplicate-requests

This middleware aims to avoid duplicated requests made the client, due to lack of network, or nervous and frustrated endless cliking.

Assuming the client send an unique id with every request (not duplicated requests), the middleware will send an error or resend the content of the previous request if a request already arrived have the same id.

Usage :

import duplicate from "duplicate-requests";
// or
const duplicate = require("duplicate-requests").default;

const express = require("express");
const app = express();

app.use(duplicate({
    expiration: "2h",
    property: "id",
    prefix: "root"
}));

app.get("/", (req, res) => res.end("Hey!"));

app.listen(8080, () => console.log("Listening!"));

Options

{
  expiration: "2h", /* Expiration time of the request in memory
                     * should be an int followed by ms, s, m, h, d, w,
                     */
  property: "id", /* Property which contains the id
                   * should be a string or a function 
                   * with a req paramater which returns a string
                   */
  prefix: "article.add", // Prefix to group requests in storage
  errorHandling: {
    statusCode: 429, // The status code to send if request is duplicated
    json: {} // Javascript plain object to send if request is duplicated
  },
  connectionUri: "" // Leave empty to store object in memory, or use redis:// or mongodb://
}

External storage

If you want to use an external storage (currently supported are Redis and MongoDB), you need to install one of the following package :

yarn add @keyv/mongo
yarn add @keyv/redis

Todo

  • Custom error

  • Parameter to cache request and don't send error

  • Timestamp parser (1d, 3h)

  • Pick id from body

  • Integration test for middleware

About

Express middleware to avoid duplicates requests made by client

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published