# request-to-file

> Installation: ``` npm install request-to-file ``` ### Description:

Latest version **3.0.0** (published 2021-07-17) · ISC license · 0 weekly downloads

## Install

```sh
npm install request-to-file
pnpm add request-to-file
yarn add request-to-file
bun add request-to-file
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 3.0.0 |
| Published | 2021-07-17 |
| First published | 2020-10-13 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 10.7 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | jackbrown9375@gmail.com |
| Maintainers | jackbrown9375 |
| Keywords | express, request-to-file, request-save |

## Links

- npm: https://www.npmjs.com/package/request-to-file
- npm.io page: https://npm.io/package/request-to-file

## Dependencies (1)

- [node-fetch](https://npm.io/package/node-fetch.md) ^2.6.1

## Recent versions

- 3.0.0 (latest) — 2021-07-17
- 2.0.5 — 2021-01-05
- 2.0.4 — 2020-11-19
- 2.0.3 — 2020-10-29
- 2.0.2 — 2020-10-21
- 2.0.1 — 2020-10-21
- 2.0.0 — 2020-10-21
- 1.0.6 — 2020-10-14
- 1.0.5 — 2020-10-14
- 1.0.4 — 2020-10-14
- 1.0.3 — 2020-10-14
- 1.0.2 — 2020-10-14
- 1.0.1 — 2020-10-13
- 1.0.0 — 2020-10-13

## README

# request-to-file
Installation:
```
npm install request-to-file 
```
### Description:

Middleware for express js servers, which converts the requests 
that arrive at the server in js files, to later analyze, edit,
resend them to the API.

### Operating mode:
When processing a request (request) in express server
this middleware is executed which receives as parameters
a function that will define if the request is saved or not,
and also a path of our system in which the requests will be saved
in js format. (Binary files in a request will be not saved with
the request)


### Usage

```js
const requestToFile = require("request-to-file");

require('express')().use(
  requestToFile.start(
    {
      /*
        Optional parameter
        if you want to use saved files from your production server 
        on your localhost api can set `newUrlBase` to your local server url
      */
      newUrlBase: '',
   

      /*
        Mandatory parameter
        `shouldBeSaved` function should return one folder path where files
        will be saved,
        or `false` if you dont need to save that request
      */
      shouldBeSaved: function (req, res) {
        if (
          /* some checks */
        ) {
          return 'valid-path-where-files-will-be-saved';
        } else {
          return false;
        }
      },


      /*
        Optional parameter
        If you want to save the request by yourself use the function
        `customSave`, it receive the final file content of the request
      */
      customSave: function(finalString,req,res){
        /* some custom actions with the request string*/
      }
    }
    
  )
)
```




### Full example with an express js server
```js 
const express = require('express');
const app = express();
const port = 3000;


//---start-module-usage----------------------
const requestToFile=require("request-to-file");
app.use(
     requestToFile.start(
      {
        newUrlBase: "http://localhost:3000",
        shouldBeSaved: function (req, res) {
          if (
            req.method == "GET" ||    
            req.method == "POST" ||    
            req.method == "DELETE" ||
            req.method == "PATCH" ||
            res.statusCode == 500
          ) {
            return "../requests";
          } else {
            return false;
          }
        },
        customSave: function(finalString,req,res){
          console.log(finalString);
          if (req.url.startsWith("/v1/payment") && res.statusCode==400){
            /** 
            * send the string to my email( for example )
            */
          }
        }
      }
    )
  );
//---end-module-usage---------------------

app.get('/', (req, res) => {
  res.send('Hello World!');
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
})
```

In this example, requests with verb "GET", "POST", "DELETE", "PATCH" or the "statusCode" of the api response is 500 are saved in files.
The files are stored in the path "../requests"  targeting the api 'http://localhost:3000'.
The `customSave` function is printing the final structure (See: `Example of a stored request` section)







### File name format: 

YYYY-MM-DDTHH-MM-SS.mmmZ< hash >-< responseStatus >-< VERB >-< route >.js
< hash >: request id, to avoid saving the same request twice. 
< responseStatus >: Response code from the polled server.
< VERB >: Verb of the request.
< route >: endpoint url.

example:
2020-10-13T15-18-07.378Z75f97f4d650fac507ad93956c472fee6-200-GET--v1-product.js


### Example of a stored request

```js
let requestToFile=require("request-to-file")

return requestToFile.reExecute({
    url: "http://localhost:8000/v1/product",
    method: "GET",
    headers: {
    "host": "localhost:8000",
    "connection": "keep-alive",
    "accept": "application/json, text/plain, */*",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.80 Safari/537.36",
    "origin": "http://localhost:4201",
    "referer": "http://localhost:4201/",
    "accept-encoding": "gzip, deflate",
    "accept-language": "en-US,en;q=0.9,es;q=0.8"
},
  query: {
    "limit": "10",
    "offset": "0",
    "order": "-createdAt",
    "filter": {
        "$and": {
            "price": "20.00"
        }
    }
},
  body: {

}
}
).then(function(data){
    console.log("Status: ", data.status)
    return data.text().then(function (dataText) {
        try {
            console.log(JSON.stringify(JSON.parse(dataText), null, 2));
        } catch (e) {
            console.log(dataText)
        } 
    }) 
})
```

To execute a stored request, just go to the folder where requests are stored
and execute a file like a regular js file.

If you are using linux, i recommend to use Geany to edit/execute the js files.

---
_Source: https://npm.io/package/request-to-file · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
