{"_id":"restful-react","_rev":"199-7d246e3508e2836b507b297d99f71512","name":"restful-react","dist-tags":{"latest":"15.9.4","next":"9.0.1","canary":"15.4.1-g1d6980d","without-cli":"15.9.4-without-cli"},"versions":{"3.0.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"3.0.1","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/tejasq/restful-react.git"},"scripts":{"watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build"},"lint-staged":{".(md)":["prettier --write","doctoc","git add"],".(tsx)":["tslint --fix","prettier --write","git add"]},"devDependencies":{"@types/react":"^16.4.1","doctoc":"^1.3.1","husky":"^0.14.3","jest":"^23.1.0","lint-staged":"^7.2.0","prettier":"^1.13.5","rollup":"^0.61.2","rollup-plugin-typescript2":"^0.15.0","ts-jest":"^22.4.6","tslint":"^5.10.0","typescript":"^3.0.0-dev.20180623"},"dependencies":{"react":"^16.4.1"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"45957a93ebf086e0418b42b4d1cf5889c1300a3c","homepage":"https://github.com/tejasq/restful-react#readme","_id":"restful-react@3.0.1","_npmVersion":"6.1.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-nNoLHwMV2bHbiGjoMPN8b0IEUynhmrfyoAMJF3A8YUelW1mtkQe/RoswgdIH3s8BX/dYeodWyu9GACt9WrVMcw==","shasum":"ca316c8fbdfb1890ab1d70e57acd5ceaf79d5b29","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-3.0.1.tgz","fileCount":6,"unpackedSize":45743,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbOlFZCRA9TVsSAnZWagAASnwP/ik5I+01hY8GP9X2ruhN\nNKP0XJ1qrRvE8mvCMOB8eGJd+92sNVaHAXyngE5TL8czKB/UUIdQzW7iGQ/V\n3H0VFfRHPkkQp9SlpkyfFW+5CD5FD/+hy17JUFY/CuHQAf2EYkBUiBBUDq1g\n4tKL4NmYVxFflgPKoys18ocwPWlwK0kHCb92fXRmmyMelj3qGrZSLcSTldDZ\n7NuLxipKyXRwM1CuBas9Gk6uTu1aqQgea7VmTUqKLYVHLve677LMK/y4Desq\n1RlAcWXoMniaoheRXPvSW/0RUcYkcl1w3mrTrRe+Uih9NgNVMck5LWdrrvRC\n4CIXw52+aKjsV2NDEtV4KZnbNGHzIXWhTz34E7X9CRrTDd0Blw0aMMn99ZK8\nN3a2DiDFT9hpxYiTYOpvVTZ95U0SVch8WHvb4TWozNkLO9liUzkQ2PZD6YbL\nQ787pMVMlVGFp0HEU9/ptio5o1oAF9SESU/LvMkS4MxP/g643oupwRqKh7lq\nFd6B/q099C2V4IQkn8OxxIlHvVYs0tjtpYmgJiPGRpMOaOfyZgWkV9ojsUm0\nS+u6Bb+JiBHTDVLTVb5t5Fr3ypNgRmN9xBrs+13PK1Y05YXVCgmUTXbnSQ2b\n45CsbqTzDO3M+2HiyiQwVb0ePnq+cIaytSGdI9JIBltnGduhBkC0SR1AMIPJ\nlN+d\r\n=F6bt\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCrs/WKxZzMiTHV/Hm62GJH9XCUaOad34MnZyTc5H7X1QIgDDt+bfzcAruEu0EHOzxBw0G4Gk2CrKa3VweM3ocVPOw="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_3.0.1_1530548569714_0.11349510691507181"},"_hasShrinkwrap":false},"3.0.2":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"3.0.2","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build"},"lint-staged":{".(md)":["prettier --write","doctoc","git add"],".(tsx)":["tslint --fix","prettier --write","git add"]},"devDependencies":{"@types/react":"^16.4.1","doctoc":"^1.3.1","husky":"^0.14.3","jest":"^23.1.0","lint-staged":"^7.2.0","prettier":"^1.13.5","rollup":"^0.61.2","rollup-plugin-typescript2":"^0.15.0","ts-jest":"^22.4.6","tslint":"^5.10.0","typescript":"^3.0.0-dev.20180623"},"dependencies":{"react":"^16.4.1"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"f36440093227a7cd2e3591d6ad21eb562c4d6914","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@3.0.2","_npmVersion":"6.1.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-hpwOImhYoje08LwZPPRpAC0Z0xji9prVqtblsdwySma6VNicG3twbhm0weo6H/MEIIxgL7t9fppikCrIFsbP+Q==","shasum":"658a6000349b902adbfc0896ad0350ed5c256ec6","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-3.0.2.tgz","fileCount":7,"unpackedSize":46451,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbOlaLCRA9TVsSAnZWagAAky4P/iz6fNkzq6DEV/7KEmZC\n6HlmQrwY+yA7V1FP111ARCags2EuHFSsD9QgbdpBqZRA3L8T4fpFoqW2K6rD\nzjb6oZqg9RU+V84nDa+Iyr0W8roG184puG3bQO65fRsY59g88bIWBemhkhbz\nyOQiswiJCDuwUcH6+Mb1d8tBP5JmUuxMs8LqqKVVTVeD7YTudUloSHIjE3bT\nRxKHB8rJ/aVYIG/it/c/NRuZwpHkZe54G7aLXxfbQItuxdHYQjJA1CaNlIEv\n89wQoESmIHnJX+SLzLQLMhzRC0UUpuUzqPswW0S+i3XgzvbT+E+3LnzTQFDR\njxSD5Hsx7C05ufLi0a//+I02Aj+9fv7BL1R5RlHPER9NoO/k8A7gmOpQ36SQ\nTmu2CtPG9kZFLFrrE7VkJ7tWylF2Om3wrwB0tXv1Z44dBqOklPq/TSSD7ZOx\nnhPDb0Delo0BEsP8NYdw0/s1u21LF6q4cL5xvn4UGFaawkBdMpSEuJvInCMb\njhorOs1mhaZWvtZXERaUjI07W4022sDFrknpLirLooYNDQa8mWkCYkskAObC\ndQ141rLkJYPOuXiyReOAphRlm9PGElONzF/hLLVEZiugExTe9qGiV+6cj2My\nUQK0qLlWkJkRq/PSLDzvqStbnFutShcIcarfC9Kr+dEXoQDFvRSYjpc2WQH0\nr0ht\r\n=Xno1\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIBXkk3mb2PG7GkhGtaAOviZIwBBugWfOeYmKosa4peXkAiEAsX14kqzuE0eaOm5n47ia3VF8aX2HdeoDsmqRlFXKkFQ="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_3.0.2_1530549898983_0.9816962948802213"},"_hasShrinkwrap":false},"3.1.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"3.1.0","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build"},"lint-staged":{".(md)":["prettier --write","doctoc","git add"],".(tsx)":["tslint --fix","prettier --write","git add"]},"devDependencies":{"@types/react":"^16.4.1","doctoc":"^1.3.1","husky":"^0.14.3","jest":"^23.1.0","lint-staged":"^7.2.0","prettier":"^1.13.5","rollup":"^0.61.2","rollup-plugin-typescript2":"^0.15.0","ts-jest":"^22.4.6","tslint":"^5.10.0","typescript":"^3.0.0-dev.20180623"},"dependencies":{"react":"^16.4.1"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"e3d144d6637b286ad22256523d806823a428a379","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@3.1.0","_npmVersion":"6.1.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-WPaUN1lQnQ10ZfiDczYd4/JkgwTZMv5ZKY9ojfWldLTFoKWBVIn+Ejrj6BTOpzd+j4kw3lnF010W6aLRws2zEg==","shasum":"6399a05659034b15e15ec34c9c319500d60bd2aa","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-3.1.0.tgz","fileCount":7,"unpackedSize":46818,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbP5BPCRA9TVsSAnZWagAAgesP/A7u21ANI4DSJS5/eP2n\nGdOR66mfXg72WO+KFfuTiDsjLrMSa8kpb/GF9nofMZ6r5pS5XrSMTiu7lZfk\nDK9QLmO6DUU0vwgKTcoR5g7WIH6EliTJZOpnQ/o0Tb55OI3YuTPJcZh9rURE\n1j8GIHSKe7ZjDPGFBmU7kB33C+g1w8CJjy4KhNk1gm9D7+d9Sf6UElTpJblt\nWqgtd9CcN94S0DjtIJHWgBq78qOKqYwTdh6rk8MJgTckjZYTJ1tf/yvSJssQ\nNctmIoHJdNJFonrKaYHU5WrkzKURwyw3O4N60svlJkJqQyNQpDv4Llqeta36\nevuOd9un7J8rYivG7HZ0fo/HQuDfPopC85StYuIWBvHWj9Ldqi+TnK6G8HrO\nI0J1qXkMc7+ejx0TtFTBBikHguVdJfMcsKwKN3Z1NE+6aNeRLW8BLduAXqeK\now4EfQ5bI8HleWYv7Drv17wqEn4tygXL4ehRLAN2Xm0vgC/8wd2/3enVgR0/\nKZfgPkSjm7J0CIBrCBLjkFiHpQPoeP1v0+Npj1HezpsJsUrAz3X5GHvhqoqk\nioT/kyvvcPNb8KoQISfLLjWqsLYWCC0eXudgQH9GxdCiOZjOEAAq6X/ibgXW\nlw50y3K+K0C2T0aUQUjGoEliz27zgAlpLUNLVkx+d4WVu0fABRf57e0a0wqg\nhLxq\r\n=5P/3\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIDtu1LWYHuMW4LbPUHxY/xRQRXPyFoakahD1omXsPaAVAiEA17Pb52bAmc0hYaO6wx0Sz8IrD/qRB4ZIDSEbPnzv8js="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_3.1.0_1530892367141_0.2406841617387634"},"_hasShrinkwrap":false},"4.0.0-1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.0.0-1","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix","prettier --write","git add"]},"devDependencies":{"@types/react":"^16.4.1","doctoc":"^1.3.1","husky":"^0.14.3","jest":"^23.1.0","lint-staged":"^7.2.0","prettier":"^1.13.5","rollup":"^0.61.2","rollup-plugin-typescript2":"^0.15.0","ts-jest":"^22.4.6","tslint":"^5.10.0","typescript":"^3.0.0-dev.20180623"},"dependencies":{"react":"^16.4.1"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Mutations](#mutations)\n    - [Mutations API](#mutations-api)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [TypeScript Integration](#typescript-integration)\n  - [Polling](#polling)\n    - [`Poll` API](#poll-api)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a single component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider base=\"String!\" resolve={data => data} requestOptions={{}} />;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\n<Get path=\"/cats\">\n  {data => {\n    return (\n      <div>\n        <h1>Here are my cats!</h1>\n        {data.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n\n        {/* Request BASE/cats/persian */}\n        <Get path=\"/persian\">\n          {persianCats => {\n            return (\n              <div>\n                <h2>Here are my persian cats!</h2>\n                {persianCats.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n              </div>\n            );\n          }}\n        </Get>\n      </div>\n    );\n  }}\n</Get>\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each get _can_ override its parent with other props as well: including having _specific_ `requestOptions` for each `Get` if there was a valid use case.\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>Here are all my {props.animal}s!</h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>Here are all my {props.animal}s!</h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Mutations\n\n`Get` components pass mutation functions as the third argument to their children. Consider,\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n\n            {/* Will send a DELETE request to BASE/movies/:movie.id */}\n            <button\n              onClick={_ =>\n                actions\n                  .delete(movie.id)\n                  .then(returnedData => dispatch({ type: \"DELETED_MOVIE\", payload: returnedData }))\n              }\n            >\n              Delete!\n            </button>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\nThe same mutation objects exist for all HTTP verbs, including `get`, `post`, `put`, and `patch`. Methods `post`, `put`, and `patch` all expect a body as their first argument, and all mutation functions receive `requestOptions` as their optional second argument.\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### Mutations API\n\nHere are the functions passed as the second argument to children of `Get` with their signatures.\n\n```ts\ninterface Mutations<T> {\n  get: (path?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  destroy: (id?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  post: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  put: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  patch: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n}\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Polling\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll` and `Get` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### `Poll` API\n\nBelow is the full `Poll` component API.\n\n```ts\ninterface Poll<T> {\n  /**\n   * What path are we polling on?\n   */\n  path: GetComponentProps<T>[\"path\"];\n  /**\n   * A function that gets polled data, the current\n   * states, meta information, and various actions\n   * that can be executed at the poll-level.\n   */\n  children: (data: T | null, states: States<T>, actions: Actions, meta: Meta) => React.ReactNode;\n  /**\n   * How long do we wait between requests?\n   * Value in milliseconds.\n   * Defaults to 1000.\n   */\n  interval?: number;\n  /**\n   * A stop condition for the poll that expects\n   * a boolean.\n   *\n   * @param data - The data returned from the poll.\n   * @param response - The full response object. This could be useful in order to stop polling when !response.ok, for example.\n   */\n  until?: (data: T | null, response: Response | null) => boolean;\n  /**\n   * Are we going to wait to start the poll?\n   * Use this with { start, stop } actions.\n   */\n  lazy?: GetComponentProps<T>[\"lazy\"];\n  /**\n   * Should the data be transformed in any way?\n   */\n  resolve?: GetComponentProps<T>[\"resolve\"];\n  /**\n   * We can request foreign URLs with this prop.\n   */\n  base?: GetComponentProps<T>[\"base\"];\n  /**\n   * Any options to be passed to this request.\n   */\n  requestOptions?: GetComponentProps<T>[\"requestOptions\"];\n}\n\n/**\n * Actions that can be executed within the\n * component.\n */\ninterface Actions {\n  start: () => void;\n  stop: () => void;\n}\n\n/**\n * States of the current poll\n */\ninterface States<T> {\n  /**\n   * Is the component currently polling?\n   */\n  polling: boolean;\n  /**\n   * Is the initial request loading?\n   */\n  loading: boolean;\n  /**\n   * Has the poll concluded?\n   */\n  finished: boolean;\n  /**\n   * Is there an error? What is it?\n   */\n  error?: string;\n}\n\n/**\n * Meta information returned from the poll.\n */\ninterface Meta extends GetComponentMeta {\n  /**\n   * The entire response object.\n   */\n  response: Response | null;\n}\n```\n\n### Caching\n\nThis doesn't exist yet.\nPlease contribute a solution here until something happens.\n\nThere's a general idea of checking if the results are a collection or a resource, and then:\n\n- If collection, cache.\n- If resource,\n\n  - Is resource in cached collection?\n    - update cached resource.\n\n## Contributing\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. This project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"34fe91695c20a74426a8fb3fda056d41e1e1bb2c","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.0.0-1","_npmVersion":"6.1.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-B5Rv9jl/eVHSOi1PKZrQ40JZdNi9qb2gfAlDyPAPqTglsRN/lDfwKeQYl2Xc2bnSLr4PmrB12hOEqaQZTTp4yw==","shasum":"f2c45df999dde7d835b16957a8c09478922158ed","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.0.0-1.tgz","fileCount":9,"unpackedSize":48172,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbRImDCRA9TVsSAnZWagAAEwMP/2h7BWmTJyYTlyogc8J0\nm2Xgce0QatYJkZs38QmZiSYa3WpPcRUq7ALgh55/+wotRIE0kKt4iHHZwcRL\nUuUyt28+YMLje8KHsO3KCgvSgAj8uzsJMjocSG7nfev5dVPxlF0FnH3uwasa\nffkaZTmeMxrW4sIo1v53mrvUHMjhxfppNimJRyONIZdK3PNy59NyANrOMj+6\nmndjwVlypABU7ZpvEioWL/4KiL9cWxSVz0TCHengv9XHiNqTAQxP2ifwEKw9\n5yd81a02Nc9jRMN7qxE00BzQ2+qzKk9S3dJYJjUmYUdoGQLMwE/jEjxeUfbP\n2DzO9Zc53lPSj87A9v+dnJNQPDbqfD8HA4LzEjRXDhYQSX4r4xJVmsitSenI\nxlQW9iGomS0MHBEPSk2v9JJ0257PQxnHtItmIj2SrSlv1PPafDV84NiRbi9G\ngm5He5Sao2G9jrkMlQzhl5x7fCRSAci713SNvixCQcQX0XRF53An9S9Tb5o5\nULe3jFVb7oa8t1SeAXM2M9YhWxqhWyHH/UKjZmqDT5Uu5XBgmHCqFJpdKZ9v\nu2VOogaXTFhVMXuKEyC4kE0U9tueTFHikuvLeStXAM2XT2MDn+j9uxmEaDqp\n8CWsBCJJVw04DiGWb6w8IPRZ64nVKTmU854y/WVDiTaXpnclLS1XGFyCakKo\nuKqw\r\n=zkl6\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCS2qwfQPE3xWUPxdRJJbtNd7ItJOypYSKPIe02WgzuFgIgbuSuAMMDozMCCCBEA6hTZ/vdZbG0kV3f0+wxHByuvNw="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.0.0-1_1531218306991_0.36788203542918296"},"_hasShrinkwrap":false},"4.0.0-2":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.0.0-2","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix","prettier --write","git add"]},"devDependencies":{"@types/react":"^16.4.1","doctoc":"^1.3.1","husky":"^0.14.3","jest":"^23.1.0","lint-staged":"^7.2.0","prettier":"^1.13.5","rollup":"^0.61.2","rollup-plugin-typescript2":"^0.15.0","ts-jest":"^22.4.6","tslint":"^5.10.0","typescript":"^3.0.0-dev.20180623"},"dependencies":{"react":"^16.4.1"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"1f08f5272f57a5f6c1fda7dce818945536fda06f","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.0.0-2","_npmVersion":"6.1.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-1QJpLuOQIVqOnBt/NVdeRfTAMClZaJomGGcz0oHq4Wy9NMPh60Cyf736r1PXhomsKdXfCkUqxr8q3H2rr5WGgA==","shasum":"7b0f61ba815bf2bb281c133c1e9a978f8674480e","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.0.0-2.tgz","fileCount":9,"unpackedSize":48473,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbRIzECRA9TVsSAnZWagAA9i8P/2qkZmpYqJV+pV1anjKF\neL2Fnnmt1dnYa+LzhtG2mNhQ481jA+hm/LG0gCwXO4/1v//Q+ePIzQtYuDax\nPukX6wPvHxAB9TkDtDifxXc8UiXRnIsgYQfwiGNsuDzB7WprGmeDAUGh/Q2z\nAa5rS71/wKpJKSk+zY03MAf2UIlw/T838eun2OvdUastgh3yGQ/HgYVQwX/m\nsXC/mIuzIJGFH92msDM1xpR6CxvB9icHk9sLLEnpBC+5lVotuJj/WM4N3a+v\nYd+xq1MGkaFig7BKiD8tjeFgromhqd5ydEpGTG3j51TvZ7wbjC0YUcDKwWxe\nPXMSXZLRfc1M689ytZlZ3JasZFM2AuZbrCo5iOKNs4subdZYYsTFL+XeIZZ3\nLCcpixyearNO0iFV/TrLDKrUJ4uGrbYu8Yu/lO/GLZOuqIs4sHUAjT9V0REs\nu1TA/h4O6QSwria1p931ri02Gj2OF/7nfGgFXJiDVg9Cd90ktAVPuIrlkUte\nB1qtR8Qsaw+ct3vaB+kE6kW/q+abGz0dEipuaC/LMgRo519YchgtMurpsY2q\n3Qep3xikTCxs9wi6Q2ot5FegKdmZ9F4sYJr/JawCF8ELKFinjNJL2NFdoqM7\ntRR9NoIRS5mZRt4OAWo+vROJPWhhef0nY54rdRtP0Zrx0TQDz2sKI4oc0bav\nGbBw\r\n=QyNU\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDQFXt4KHhbcLVhBZtcBwq/MSY5KAZA0xIJII7eEKEohwIhAP85/mWLR5Pc2WSVwigIH5tjR/4IY5wfmNGxsRsgoppc"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.0.0-2_1531219140009_0.7767486429352182"},"_hasShrinkwrap":false},"3.0.4":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"3.0.4","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build"},"lint-staged":{".(md)":["prettier --write","doctoc","git add"],".(tsx)":["tslint --fix","prettier --write","git add"]},"devDependencies":{"@types/react":"^16.4.1","doctoc":"^1.3.1","husky":"^0.14.3","jest":"^23.1.0","lint-staged":"^7.2.0","prettier":"^1.13.5","rollup":"^0.61.2","rollup-plugin-typescript2":"^0.15.0","ts-jest":"^22.4.6","tslint":"^5.10.0","typescript":"^3.0.0-dev.20180623"},"dependencies":{"react":"^16.4.1"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"edebd73c8454cfd10d24e130349743973cc496f8","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@3.0.4","_npmVersion":"6.1.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-5lCEuO80DeLDS/u7+5Pdc8SaBQBtPuR3lp98Tj/15MlsvcdeTzUU60G4FwFbiybmS/dATFMux54C4LyPsNoPGQ==","shasum":"775a4b4e10fb4424a3f0dc6fe612419421bbc7b7","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-3.0.4.tgz","fileCount":9,"unpackedSize":51898,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbRI03CRA9TVsSAnZWagAABRUP/if/m32DQmvWcpX12R0k\n7fB8ETNtlHPvUnlSWiLEzilIaF1sqLimFAz2CMYaMz/nH/PkScUtIT5YYqR9\nw7uO/uFqjG8m5MJVB46t2GIB3fqxQZ0VRaY6R2ImyFdaQsQwiQxSPqQ6p50f\n6QF33mrMzi6yxzvY912JLhDslVY2Jn+8+8BoxqMX1Ff+2zqkU5CVmxhmuXUF\nCFYW35N6n57nKe1K/XzJJvK2U8EFllKwzOd1Fik96gzPujUfES/zArTKeVgX\nbvo6iELhJXOzhMhXq9lq6fxVXgGsWh2nm7rFdOzePVeeSdhdV3dFwdKcnB+W\n5Ia+rqdjFqu2DiQJV1rzV1uM1ry7H7NwyH5LBRNetQa0R7xc3tjwHwLS4eE6\nxXBXpzuOwlR9tNXK3HJk4P33rxUsq0ug9il9VWVwr5TOnIV9mekfv50ouf2A\n/KcRkUxpEGjxuTj8vF4+lAre/o7inEZlyQyE0DjD3USLcrXH4+KriASa0Xir\nIRSpGgfmChCr3+4qdYH9lOPbTObbEwA2UHCScMaFAjKTgTiiFiqH9+kcrFZY\nnN7s1kSvzOpTDI8ZPMrKscIP+F4DnXiuDSYTyyPzGA11h8eN0Hnufp2GKBbT\nVHE5hUGL6Ql7qiKEVUFkZHOcjyQx9Z33NbIvp1uMkPeW7KVI+Jz1H8HEzatr\nfAH3\r\n=2EaA\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIFvvMiLFpssJ9uf1JnUMp0+vwLZBB17XTjofmFiUL7/gAiEA0yUsJUV++1YUui8e/isSyIE92W1Rnj7v0H3lmWIy36o="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_3.0.4_1531219255670_0.437376499499605"},"_hasShrinkwrap":false},"4.0.0-3":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.0.0-3","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix","prettier --write","git add"]},"devDependencies":{"@types/react":"^16.4.1","doctoc":"^1.3.1","husky":"^0.14.3","jest":"^23.1.0","lint-staged":"^7.2.0","prettier":"^1.13.5","rollup":"^0.61.2","rollup-plugin-typescript2":"^0.15.0","ts-jest":"^22.4.6","tslint":"^5.10.0","typescript":"^3.0.0-dev.20180623"},"dependencies":{"react":"^16.4.1"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Mutations](#mutations)\n    - [Mutations API](#mutations-api)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [TypeScript Integration](#typescript-integration)\n  - [Polling](#polling)\n    - [`Poll` API](#poll-api)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a single component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider base=\"String!\" resolve={data => data} requestOptions={{}} />;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\n<Get path=\"/cats\">\n  {data => {\n    return (\n      <div>\n        <h1>Here are my cats!</h1>\n        {data.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n\n        {/* Request BASE/cats/persian */}\n        <Get path=\"/persian\">\n          {persianCats => {\n            return (\n              <div>\n                <h2>Here are my persian cats!</h2>\n                {persianCats.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n              </div>\n            );\n          }}\n        </Get>\n      </div>\n    );\n  }}\n</Get>\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each get _can_ override its parent with other props as well: including having _specific_ `requestOptions` for each `Get` if there was a valid use case.\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>Here are all my {props.animal}s!</h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>Here are all my {props.animal}s!</h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Mutations\n\n`Get` components pass mutation functions as the third argument to their children. Consider,\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n\n            {/* Will send a DELETE request to BASE/movies/:movie.id */}\n            <button\n              onClick={_ =>\n                actions\n                  .delete(movie.id)\n                  .then(returnedData => dispatch({ type: \"DELETED_MOVIE\", payload: returnedData }))\n              }\n            >\n              Delete!\n            </button>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\nThe same mutation objects exist for all HTTP verbs, including `get`, `post`, `put`, and `patch`. Methods `post`, `put`, and `patch` all expect a body as their first argument, and all mutation functions receive `requestOptions` as their optional second argument.\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### Mutations API\n\nHere are the functions passed as the second argument to children of `Get` with their signatures.\n\n```ts\ninterface Mutations<T> {\n  get: (path?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  destroy: (id?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  post: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  put: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  patch: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n}\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Polling\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll` and `Get` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### `Poll` API\n\nBelow is the full `Poll` component API.\n\n```ts\ninterface Poll<T> {\n  /**\n   * What path are we polling on?\n   */\n  path: GetComponentProps<T>[\"path\"];\n  /**\n   * A function that gets polled data, the current\n   * states, meta information, and various actions\n   * that can be executed at the poll-level.\n   */\n  children: (data: T | null, states: States<T>, actions: Actions, meta: Meta) => React.ReactNode;\n  /**\n   * How long do we wait between requests?\n   * Value in milliseconds.\n   * Defaults to 1000.\n   */\n  interval?: number;\n  /**\n   * A stop condition for the poll that expects\n   * a boolean.\n   *\n   * @param data - The data returned from the poll.\n   * @param response - The full response object. This could be useful in order to stop polling when !response.ok, for example.\n   */\n  until?: (data: T | null, response: Response | null) => boolean;\n  /**\n   * Are we going to wait to start the poll?\n   * Use this with { start, stop } actions.\n   */\n  lazy?: GetComponentProps<T>[\"lazy\"];\n  /**\n   * Should the data be transformed in any way?\n   */\n  resolve?: GetComponentProps<T>[\"resolve\"];\n  /**\n   * We can request foreign URLs with this prop.\n   */\n  base?: GetComponentProps<T>[\"base\"];\n  /**\n   * Any options to be passed to this request.\n   */\n  requestOptions?: GetComponentProps<T>[\"requestOptions\"];\n}\n\n/**\n * Actions that can be executed within the\n * component.\n */\ninterface Actions {\n  start: () => void;\n  stop: () => void;\n}\n\n/**\n * States of the current poll\n */\ninterface States<T> {\n  /**\n   * Is the component currently polling?\n   */\n  polling: boolean;\n  /**\n   * Is the initial request loading?\n   */\n  loading: boolean;\n  /**\n   * Has the poll concluded?\n   */\n  finished: boolean;\n  /**\n   * Is there an error? What is it?\n   */\n  error?: string;\n}\n\n/**\n * Meta information returned from the poll.\n */\ninterface Meta extends GetComponentMeta {\n  /**\n   * The entire response object.\n   */\n  response: Response | null;\n}\n```\n\n### Caching\n\nThis doesn't exist yet.\nPlease contribute a solution here until something happens.\n\nThere's a general idea of checking if the results are a collection or a resource, and then:\n\n- If collection, cache.\n- If resource,\n\n  - Is resource in cached collection?\n    - update cached resource.\n\n## Contributing\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. This project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"fd1483924d8f5452afcf27d182619d84f0c33fd6","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.0.0-3","_npmVersion":"6.1.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-vT4z5b4/zumL6kq5ApD9gg72VKuGZTSH/C1r+uPh/RLpRatzvOvcmHM+ImkcWFP8uWtus9GLvJCWXG4E0jEEYA==","shasum":"4f69be91d81d7233895cf4e6cbbdca2c4ef94a89","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.0.0-3.tgz","fileCount":9,"unpackedSize":48473,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbRI1uCRA9TVsSAnZWagAALiEP/14DRVqcx/Sy4z18f+nC\nkhh75hp6bRKtAHHl9W35DV4Qn5U+t9jSYA112nuMgerauIzBHNfynEJsoyNd\nGRVld4J4j2qmjz70LHFbDUE2agdtcjyfVcJESp45eXEHzmcq9D7aW09LKcZG\n4kwq7uGhaw/0SUKphVAn7+doPQ4tqYcDHzTE4dzUeRYLGY0pzBYUqeV/TrbB\nXIizUvX87SqBJCHUUaPm8GjRa6nZoWN7lj6heFctv2mcmG7pORrqSZQsZTcy\nN21Ijg2PbnO57Cy8SZ9QhXxH0Lx6Od/eN1QCR7dv7hZ4LbpVSFOgK5MwzASj\nYZvdiukLINhWqguktuydnxHPepM+V/Tmz8KoZcJiaEB1LOQWDR8Pmp4R5dHt\nlnUiWQ6zGZuB+Gk94k/JI989y16LT5jfdPdro5eSlsVKvtRQLIakrHDx8A8P\nEtLkQbCkpct5BadtVhBDQxWWfU9VwJ6q5aPFEqHLJKCax8EWwj9G+iJMOaTR\ntXZRsI4fNROa+3Aef9dyV1cYeNyDs5d24LJRk42eVWf/dsFDkhTqQFZ2+hh1\nwTpKhJ1GULAtP4optnSap8AwqqJ8sdAc4se4s9Vvtb9E4zKtZ8vSHL1buAK0\nuHw9Jj2Nm58vU1EzQTea5w/Sg91WRqE2NVZr8MnSrRJOtBoY7vBxqDu+ojzj\nH27e\r\n=43T/\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIG4GjL8SDWf7dvWBfWT63yZNYXhsXR7GKl+wvAdL95wMAiBl7Ha3vBIW/qXYZoS6cTIWpdwT6aSGsuzwsph7ZJ2fJg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.0.0-3_1531219310362_0.9915587706433293"},"_hasShrinkwrap":false},"4.0.0-4":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.0.0-4","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix --project .","prettier --write","git add"]},"devDependencies":{"@types/react":"^16.4.1","doctoc":"^1.3.1","husky":"^0.14.3","jest":"^23.1.0","lint-staged":"^7.2.0","prettier":"^1.13.5","rollup":"^0.61.2","rollup-plugin-typescript2":"^0.15.0","ts-jest":"^22.4.6","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.8","typescript":"^3.1.0-dev.20180717"},"dependencies":{"react":"^16.4.1"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Mutations](#mutations)\n    - [Mutations API](#mutations-api)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [TypeScript Integration](#typescript-integration)\n  - [Polling](#polling)\n    - [`Poll` API](#poll-api)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a single component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider base=\"String!\" resolve={data => data} requestOptions={{}} />;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\n<Get path=\"/cats\">\n  {data => {\n    return (\n      <div>\n        <h1>Here are my cats!</h1>\n        {data.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n\n        {/* Request BASE/cats/persian */}\n        <Get path=\"/persian\">\n          {persianCats => {\n            return (\n              <div>\n                <h2>Here are my persian cats!</h2>\n                {persianCats.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n              </div>\n            );\n          }}\n        </Get>\n      </div>\n    );\n  }}\n</Get>\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each get _can_ override its parent with other props as well: including having _specific_ `requestOptions` for each `Get` if there was a valid use case.\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>Here are all my {props.animal}s!</h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>Here are all my {props.animal}s!</h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Mutations\n\n`Get` components pass mutation functions as the third argument to their children. Consider,\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n\n            {/* Will send a DELETE request to BASE/movies/:movie.id */}\n            <button\n              onClick={_ =>\n                actions\n                  .delete(movie.id)\n                  .then(returnedData => dispatch({ type: \"DELETED_MOVIE\", payload: returnedData }))\n              }\n            >\n              Delete!\n            </button>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\nThe same mutation objects exist for all HTTP verbs, including `get`, `post`, `put`, and `patch`. Methods `post`, `put`, and `patch` all expect a body as their first argument, and all mutation functions receive `requestOptions` as their optional second argument.\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### Mutations API\n\nHere are the functions passed as the second argument to children of `Get` with their signatures.\n\n```ts\ninterface Mutations<T> {\n  get: (path?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  destroy: (id?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  post: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  put: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  patch: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n}\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Polling\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll` and `Get` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### `Poll` API\n\nBelow is the full `Poll` component API.\n\n```ts\ninterface Poll<T> {\n  /**\n   * What path are we polling on?\n   */\n  path: GetComponentProps<T>[\"path\"];\n  /**\n   * A function that gets polled data, the current\n   * states, meta information, and various actions\n   * that can be executed at the poll-level.\n   */\n  children: (data: T | null, states: States<T>, actions: Actions, meta: Meta) => React.ReactNode;\n  /**\n   * How long do we wait between requests?\n   * Value in milliseconds.\n   * Defaults to 1000.\n   */\n  interval?: number;\n  /**\n   * A stop condition for the poll that expects\n   * a boolean.\n   *\n   * @param data - The data returned from the poll.\n   * @param response - The full response object. This could be useful in order to stop polling when !response.ok, for example.\n   */\n  until?: (data: T | null, response: Response | null) => boolean;\n  /**\n   * Are we going to wait to start the poll?\n   * Use this with { start, stop } actions.\n   */\n  lazy?: GetComponentProps<T>[\"lazy\"];\n  /**\n   * Should the data be transformed in any way?\n   */\n  resolve?: GetComponentProps<T>[\"resolve\"];\n  /**\n   * We can request foreign URLs with this prop.\n   */\n  base?: GetComponentProps<T>[\"base\"];\n  /**\n   * Any options to be passed to this request.\n   */\n  requestOptions?: GetComponentProps<T>[\"requestOptions\"];\n}\n\n/**\n * Actions that can be executed within the\n * component.\n */\ninterface Actions {\n  start: () => void;\n  stop: () => void;\n}\n\n/**\n * States of the current poll\n */\ninterface States<T> {\n  /**\n   * Is the component currently polling?\n   */\n  polling: boolean;\n  /**\n   * Is the initial request loading?\n   */\n  loading: boolean;\n  /**\n   * Has the poll concluded?\n   */\n  finished: boolean;\n  /**\n   * Is there an error? What is it?\n   */\n  error?: string;\n}\n\n/**\n * Meta information returned from the poll.\n */\ninterface Meta extends GetComponentMeta {\n  /**\n   * The entire response object.\n   */\n  response: Response | null;\n}\n```\n\n### Caching\n\nThis doesn't exist yet.\nPlease contribute a solution here until something happens.\n\nThere's a general idea of checking if the results are a collection or a resource, and then:\n\n- If collection, cache.\n- If resource,\n\n  - Is resource in cached collection?\n    - update cached resource.\n\n## Contributing\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. This project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"7e255dd333c884e92faea6d11f461d5fb3c2b9f4","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.0.0-4","_npmVersion":"6.2.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-pymqhwtTG+ZD5FNB+reV1WPgyKfCtsx8bV3XO+o9eVy7vPuYgBT/hk7LE12uD5cAeOlquqBL3SmjWoCaerRfTg==","shasum":"4219d7597515d43f929f363bb77d56e47351cf14","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.0.0-4.tgz","fileCount":9,"unpackedSize":48951,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbT0HOCRA9TVsSAnZWagAAY9gQAIvfEDHCOQ0rFB9edwdd\nJGyCRaS/dFBlHaxLUbMXdFHDr9WKXKlsRlLZmK3XnuxAwR1p7LrnQ2k2QCof\n7KhmesaDo5tUnMjbileZ0P41gUEntfTwYeckCWf/Ss17whSJeH4ALzPeyuau\nNtH7C85VxcopZfLbWrnOzfiICXTPUrAn2Mnb/S1HhsLI3zHoQSHORv78Co4m\nhGFldrUIbTFuydw+jWsYwYASBlwtfwpkgM+ddMnPOvAQJSvl1Ex1aS1Bbg46\n+WMRtEXM66Iaf/ka/cdEPtBOspF59HQNqOEOq5Bxy5HYGNVPRQOWv7n6QT1d\nQa8SwUSxRJDjza7jB7vuszW91ZL6KVMrFlnSbiaI3QS+/zrpTECztNJRZHfp\npSbRG5LNAVvjfKmXg1wUDO1zS5VLGjsO56I/R+BRpGWvRi5hvTPWtkkz/Otk\njikV41a0EcQq1lsNMTU/T9WcEAHL37yLlqIRbyKQmKm5PkpgLXIA61ctmpyM\nlDarEhng8yf4/inWLOSLfZDVr40bL2K4O5uxEhBhtp3TgqniNOQg3CdfJICp\nmy9EhSTUfRB1DAtoGxdSIqSUNatO7iz4cP8h+MTNBy5ELtdqkUqo2uVPjldk\nqfIYS8RU1ED8QjgyqiHqOz2Ee4r1s35hXFQrOXeD/K6ISqSwCsaLTVPDUGsH\nkBzT\r\n=CbO8\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQD/+aSg6xvfGo1ncwWRKaRnhWyA/2/1rBHrd2H8IRerfQIhAN9dSWJfbXuhc8yqyjkbI0TQTqfUu1L9WlVudPfXwV4P"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.0.0-4_1531920846422_0.9147238233526058"},"_hasShrinkwrap":false},"4.0.0-5":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.0.0-5","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix --project .","prettier --write","git add"]},"devDependencies":{"@types/react":"^16.4.1","doctoc":"^1.3.1","husky":"^0.14.3","jest":"^23.1.0","lint-staged":"^7.2.0","prettier":"^1.13.5","rollup":"^0.61.2","rollup-plugin-typescript2":"^0.15.0","ts-jest":"^22.4.6","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.8","typescript":"^2.9.2"},"dependencies":{"react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Mutations](#mutations)\n    - [Mutations API](#mutations-api)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [TypeScript Integration](#typescript-integration)\n  - [Polling](#polling)\n    - [`Poll` API](#poll-api)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a single component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider base=\"String!\" resolve={data => data} requestOptions={{}} />;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\n<Get path=\"/cats\">\n  {data => {\n    return (\n      <div>\n        <h1>Here are my cats!</h1>\n        {data.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n\n        {/* Request BASE/cats/persian */}\n        <Get path=\"/persian\">\n          {persianCats => {\n            return (\n              <div>\n                <h2>Here are my persian cats!</h2>\n                {persianCats.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n              </div>\n            );\n          }}\n        </Get>\n      </div>\n    );\n  }}\n</Get>\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each get _can_ override its parent with other props as well: including having _specific_ `requestOptions` for each `Get` if there was a valid use case.\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>Here are all my {props.animal}s!</h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>Here are all my {props.animal}s!</h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Mutations\n\n`Get` components pass mutation functions as the third argument to their children. Consider,\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n\n            {/* Will send a DELETE request to BASE/movies/:movie.id */}\n            <button\n              onClick={_ =>\n                actions\n                  .delete(movie.id)\n                  .then(returnedData => dispatch({ type: \"DELETED_MOVIE\", payload: returnedData }))\n              }\n            >\n              Delete!\n            </button>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\nThe same mutation objects exist for all HTTP verbs, including `get`, `post`, `put`, and `patch`. Methods `post`, `put`, and `patch` all expect a body as their first argument, and all mutation functions receive `requestOptions` as their optional second argument.\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### Mutations API\n\nHere are the functions passed as the second argument to children of `Get` with their signatures.\n\n```ts\ninterface Mutations<T> {\n  get: (path?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  destroy: (id?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  post: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  put: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  patch: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n}\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Polling\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll` and `Get` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### `Poll` API\n\nBelow is the full `Poll` component API.\n\n```ts\ninterface Poll<T> {\n  /**\n   * What path are we polling on?\n   */\n  path: GetComponentProps<T>[\"path\"];\n  /**\n   * A function that gets polled data, the current\n   * states, meta information, and various actions\n   * that can be executed at the poll-level.\n   */\n  children: (data: T | null, states: States<T>, actions: Actions, meta: Meta) => React.ReactNode;\n  /**\n   * How long do we wait between requests?\n   * Value in milliseconds.\n   * Defaults to 1000.\n   */\n  interval?: number;\n  /**\n   * A stop condition for the poll that expects\n   * a boolean.\n   *\n   * @param data - The data returned from the poll.\n   * @param response - The full response object. This could be useful in order to stop polling when !response.ok, for example.\n   */\n  until?: (data: T | null, response: Response | null) => boolean;\n  /**\n   * Are we going to wait to start the poll?\n   * Use this with { start, stop } actions.\n   */\n  lazy?: GetComponentProps<T>[\"lazy\"];\n  /**\n   * Should the data be transformed in any way?\n   */\n  resolve?: GetComponentProps<T>[\"resolve\"];\n  /**\n   * We can request foreign URLs with this prop.\n   */\n  base?: GetComponentProps<T>[\"base\"];\n  /**\n   * Any options to be passed to this request.\n   */\n  requestOptions?: GetComponentProps<T>[\"requestOptions\"];\n}\n\n/**\n * Actions that can be executed within the\n * component.\n */\ninterface Actions {\n  start: () => void;\n  stop: () => void;\n}\n\n/**\n * States of the current poll\n */\ninterface States<T> {\n  /**\n   * Is the component currently polling?\n   */\n  polling: boolean;\n  /**\n   * Is the initial request loading?\n   */\n  loading: boolean;\n  /**\n   * Has the poll concluded?\n   */\n  finished: boolean;\n  /**\n   * Is there an error? What is it?\n   */\n  error?: string;\n}\n\n/**\n * Meta information returned from the poll.\n */\ninterface Meta extends GetComponentMeta {\n  /**\n   * The entire response object.\n   */\n  response: Response | null;\n}\n```\n\n### Caching\n\nThis doesn't exist yet.\nPlease contribute a solution here until something happens.\n\nThere's a general idea of checking if the results are a collection or a resource, and then:\n\n- If collection, cache.\n- If resource,\n\n  - Is resource in cached collection?\n    - update cached resource.\n\n## Contributing\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. This project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"77c331b4e94c816d52c4c9cc8036854c9d831a8a","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.0.0-5","_npmVersion":"6.2.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-Fwmz4nHLGNEfKT//ns8dfDtPybhciI1J9VyL1U7phwSkPThiLZklYxh3xjNqSdUMBMK++vKCxcr9/24bvtsWXQ==","shasum":"6362f997741d1c43641be6d7d6976cbf9f17b038","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.0.0-5.tgz","fileCount":9,"unpackedSize":49947,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbUKCeCRA9TVsSAnZWagAAxxcP/A5fqomATTd7gZBMBUCc\nQfprUBmw064CBQy5wggXTFU+Vo4IIKJwI4LERPhXCNpNNLBSBTvA+NVZevyl\nEMyimoBT4c0mJQhgrwky/Zb0YM2Aymx5efjqIjPkN+issfsaYAKafizkqtQT\nfxkRESP4TtRQfImNlzdiQjuoJwTb6uh5U2FqgnB0kdoflxRSgy1U6CiwELHO\nqr8SfVHIDn5U/QlmM/1fabiRBlwg0cOV7eGqm0Txh0eWte+W8Pm+rCgvBcvt\nrl9maP81JsSB9oZjEX6TMD0jRH8pt87HBpfRsPL/qK7HCyadpKLDq0gOXQdA\nD+5kdgOFG19uqkse/DHWmw6YFJTYa51MMtzWj1tA/T9+20bGQEJb4v/knVDh\nOlNQYe3/8bb/FvRNdvzSRpUxOnE8bkQ2DTibKzSte/nVkULsKTIHeQKuoEwx\nN2+PsCmVE3hIEJHg57rtXSepW7w5kh/qaahgMQnclVznnVCxo8WSE034/v1d\ng0MBiRb31nEYrjVt8igroOX1XSa+WkH2r9blHhC5uUQ7fTsD9xWKy8l8hu/i\npw74En6W10bBEwoqkQk68DEINJfBtm3QxrLubqyXjo4oKdFXSB9pmmNW1WCQ\nfg7037mVJqBW52FycBsOuDmN7t5s8cnJrrwXErTecPZhjWDZCixNCOLrITl6\nr/dh\r\n=wNdH\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCmgDOcsOwfdNv4uJ2gLm6ymBL9Wsm0l8OTKfOkoEqo6QIgRzPksQtZMiSMpriEVLkw9JKBvTiFHkJ9+gPNFmUQU4E="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.0.0-5_1532010654494_0.6473366962334286"},"_hasShrinkwrap":false},"4.0.0-6":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.0.0-6","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix --project .","prettier --write","git add"]},"devDependencies":{"@types/react":"^16.4.1","doctoc":"^1.3.1","husky":"^0.14.3","jest":"^23.1.0","lint-staged":"^7.2.0","prettier":"^1.13.5","rollup":"^0.61.2","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^22.4.6","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.8","typescript":"^2.9.2"},"dependencies":{"react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Mutations](#mutations)\n    - [Mutations API](#mutations-api)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [TypeScript Integration](#typescript-integration)\n  - [Polling](#polling)\n    - [`Poll` API](#poll-api)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a single component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider base=\"String!\" resolve={data => data} requestOptions={{}} />;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\n<Get path=\"/cats\">\n  {data => {\n    return (\n      <div>\n        <h1>Here are my cats!</h1>\n        {data.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n\n        {/* Request BASE/cats/persian */}\n        <Get path=\"/persian\">\n          {persianCats => {\n            return (\n              <div>\n                <h2>Here are my persian cats!</h2>\n                {persianCats.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n              </div>\n            );\n          }}\n        </Get>\n      </div>\n    );\n  }}\n</Get>\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each get _can_ override its parent with other props as well: including having _specific_ `requestOptions` for each `Get` if there was a valid use case.\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>Here are all my {props.animal}s!</h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>Here are all my {props.animal}s!</h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Mutations\n\n`Get` components pass mutation functions as the third argument to their children. Consider,\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n\n            {/* Will send a DELETE request to BASE/movies/:movie.id */}\n            <button\n              onClick={_ =>\n                actions\n                  .delete(movie.id)\n                  .then(returnedData => dispatch({ type: \"DELETED_MOVIE\", payload: returnedData }))\n              }\n            >\n              Delete!\n            </button>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\nThe same mutation objects exist for all HTTP verbs, including `get`, `post`, `put`, and `patch`. Methods `post`, `put`, and `patch` all expect a body as their first argument, and all mutation functions receive `requestOptions` as their optional second argument.\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### Mutations API\n\nHere are the functions passed as the second argument to children of `Get` with their signatures.\n\n```ts\ninterface Mutations<T> {\n  get: (path?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  destroy: (id?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  post: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  put: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  patch: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n}\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Polling\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll` and `Get` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### `Poll` API\n\nBelow is the full `Poll` component API.\n\n```ts\ninterface Poll<T> {\n  /**\n   * What path are we polling on?\n   */\n  path: GetComponentProps<T>[\"path\"];\n  /**\n   * A function that gets polled data, the current\n   * states, meta information, and various actions\n   * that can be executed at the poll-level.\n   */\n  children: (data: T | null, states: States<T>, actions: Actions, meta: Meta) => React.ReactNode;\n  /**\n   * How long do we wait between requests?\n   * Value in milliseconds.\n   * Defaults to 1000.\n   */\n  interval?: number;\n  /**\n   * A stop condition for the poll that expects\n   * a boolean.\n   *\n   * @param data - The data returned from the poll.\n   * @param response - The full response object. This could be useful in order to stop polling when !response.ok, for example.\n   */\n  until?: (data: T | null, response: Response | null) => boolean;\n  /**\n   * Are we going to wait to start the poll?\n   * Use this with { start, stop } actions.\n   */\n  lazy?: GetComponentProps<T>[\"lazy\"];\n  /**\n   * Should the data be transformed in any way?\n   */\n  resolve?: GetComponentProps<T>[\"resolve\"];\n  /**\n   * We can request foreign URLs with this prop.\n   */\n  base?: GetComponentProps<T>[\"base\"];\n  /**\n   * Any options to be passed to this request.\n   */\n  requestOptions?: GetComponentProps<T>[\"requestOptions\"];\n}\n\n/**\n * Actions that can be executed within the\n * component.\n */\ninterface Actions {\n  start: () => void;\n  stop: () => void;\n}\n\n/**\n * States of the current poll\n */\ninterface States<T> {\n  /**\n   * Is the component currently polling?\n   */\n  polling: boolean;\n  /**\n   * Is the initial request loading?\n   */\n  loading: boolean;\n  /**\n   * Has the poll concluded?\n   */\n  finished: boolean;\n  /**\n   * Is there an error? What is it?\n   */\n  error?: string;\n}\n\n/**\n * Meta information returned from the poll.\n */\ninterface Meta extends GetComponentMeta {\n  /**\n   * The entire response object.\n   */\n  response: Response | null;\n}\n```\n\n### Caching\n\nThis doesn't exist yet.\nPlease contribute a solution here until something happens.\n\nThere's a general idea of checking if the results are a collection or a resource, and then:\n\n- If collection, cache.\n- If resource,\n\n  - Is resource in cached collection?\n    - update cached resource.\n\n## Contributing\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. This project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"8c317daf6ec7c023acb7e2efa5d09cde2235ecd9","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.0.0-6","_npmVersion":"6.2.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-Y7Ve4+69E98W7/BVjs95+eC31H2H1xb+f3r9LcDIRkoNGm3y7pHTvSaTkAQe4yzjTu6j6NzEodz0kEAr/ic5MA==","shasum":"49e87052de6e43b0d9edf57588cd9467ebd37a3a","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.0.0-6.tgz","fileCount":9,"unpackedSize":51034,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbYanlCRA9TVsSAnZWagAAIIcP/39y+UfZYsyVIMMa9/lg\nzZo4IlkD9l5ngmQrPKQTvztwrJnxSMzL/zPPATiWEIxGWru99i0e47mh7nDZ\n9gv/X/Wp1q/QJE4cOyXPtkoX+OO3m6N026cj8hGZPcprervETuCor8rnmo1O\nBwBi+Hw5kg67nE1EQXXz+SmsCRXOPV+Kn1Nv+Ll6+/dl4E0jYXSoB54hMthY\nwnQUET0x9INdKgNKLGiO+PlbJgO0Mbo7CAOeGB9yTby1CaxJ6lWAmHney2Os\nXtTS9x3dbjMCnmtSwiuKP5ShvKTcsxL2/OpOQ65hJa5oGDjyvbqFGKUyym1O\nvm1tkUUTV3i3ITbnnisDfgtRqKhHLkhEzPMGJoQ/hIShjkGo94gl3trgu9c5\nNEWiTgqYS7Hb1tlwmrWrfPPMb2qMhJV7izryuigF+vN2/kUhsR5CwlcIOMuZ\nUtTXeFQdjYUl6okwyWoOpXpRmS5RnD/ANMNBqkdmOM1NvjHbQ9vSlLlphQ/G\nb0UtZ+IP6rLyarpsb1hWWGo9HrIyoN+vSXWZvqoRTeDx9xuY20oNWAFq1HWi\nqz11rU0DOaYVU8Uo/Rk/Z9H7rJQdVea+uD/crzQPJQh6nySNzxBIuAm7+ctZ\nqQPQtG3WGDfFGTCfNYizUU8ycV1kc7aUSKmyX6LyyXCnib0A07nylWjCBvw4\ng7oP\r\n=Qobd\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDy+P3xW69aagmXTc4ZzcAi/+XZrRk5DhiS1BhJoRrAcQIhAPK6FFb65xpHUQk+K7ODItmcvgJ32B8tWlPC2L+JGvXl"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.0.0-6_1533127140756_0.32174868240326004"},"_hasShrinkwrap":false},"4.0.0-7":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.0.0-7","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix --project .","prettier --write","git add"]},"devDependencies":{"@types/react":"^16.4.1","doctoc":"^1.3.1","husky":"^0.14.3","jest":"^23.1.0","lint-staged":"^7.2.0","prettier":"^1.13.5","rollup":"^0.63.5","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^22.4.6","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.8","typescript":"^2.9.2"},"dependencies":{"react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Mutations](#mutations)\n    - [Mutations API](#mutations-api)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [TypeScript Integration](#typescript-integration)\n  - [Polling](#polling)\n    - [`Poll` API](#poll-api)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a single component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider base=\"String!\" resolve={data => data} requestOptions={{}} />;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\n<Get path=\"/cats\">\n  {data => {\n    return (\n      <div>\n        <h1>Here are my cats!</h1>\n        {data.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n\n        {/* Request BASE/cats/persian */}\n        <Get path=\"/persian\">\n          {persianCats => {\n            return (\n              <div>\n                <h2>Here are my persian cats!</h2>\n                {persianCats.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n              </div>\n            );\n          }}\n        </Get>\n      </div>\n    );\n  }}\n</Get>\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each get _can_ override its parent with other props as well: including having _specific_ `requestOptions` for each `Get` if there was a valid use case.\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>Here are all my {props.animal}s!</h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>Here are all my {props.animal}s!</h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Mutations\n\n`Get` components pass mutation functions as the third argument to their children. Consider,\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n\n            {/* Will send a DELETE request to BASE/movies/:movie.id */}\n            <button\n              onClick={_ =>\n                actions\n                  .delete(movie.id)\n                  .then(returnedData => dispatch({ type: \"DELETED_MOVIE\", payload: returnedData }))\n              }\n            >\n              Delete!\n            </button>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\nThe same mutation objects exist for all HTTP verbs, including `get`, `post`, `put`, and `patch`. Methods `post`, `put`, and `patch` all expect a body as their first argument, and all mutation functions receive `requestOptions` as their optional second argument.\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### Mutations API\n\nHere are the functions passed as the second argument to children of `Get` with their signatures.\n\n```ts\ninterface Mutations<T> {\n  get: (path?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  destroy: (id?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  post: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  put: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  patch: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n}\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Polling\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll` and `Get` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### `Poll` API\n\nBelow is the full `Poll` component API.\n\n```ts\ninterface Poll<T> {\n  /**\n   * What path are we polling on?\n   */\n  path: GetComponentProps<T>[\"path\"];\n  /**\n   * A function that gets polled data, the current\n   * states, meta information, and various actions\n   * that can be executed at the poll-level.\n   */\n  children: (data: T | null, states: States<T>, actions: Actions, meta: Meta) => React.ReactNode;\n  /**\n   * How long do we wait between requests?\n   * Value in milliseconds.\n   * Defaults to 1000.\n   */\n  interval?: number;\n  /**\n   * A stop condition for the poll that expects\n   * a boolean.\n   *\n   * @param data - The data returned from the poll.\n   * @param response - The full response object. This could be useful in order to stop polling when !response.ok, for example.\n   */\n  until?: (data: T | null, response: Response | null) => boolean;\n  /**\n   * Are we going to wait to start the poll?\n   * Use this with { start, stop } actions.\n   */\n  lazy?: GetComponentProps<T>[\"lazy\"];\n  /**\n   * Should the data be transformed in any way?\n   */\n  resolve?: GetComponentProps<T>[\"resolve\"];\n  /**\n   * We can request foreign URLs with this prop.\n   */\n  base?: GetComponentProps<T>[\"base\"];\n  /**\n   * Any options to be passed to this request.\n   */\n  requestOptions?: GetComponentProps<T>[\"requestOptions\"];\n}\n\n/**\n * Actions that can be executed within the\n * component.\n */\ninterface Actions {\n  start: () => void;\n  stop: () => void;\n}\n\n/**\n * States of the current poll\n */\ninterface States<T> {\n  /**\n   * Is the component currently polling?\n   */\n  polling: boolean;\n  /**\n   * Is the initial request loading?\n   */\n  loading: boolean;\n  /**\n   * Has the poll concluded?\n   */\n  finished: boolean;\n  /**\n   * Is there an error? What is it?\n   */\n  error?: string;\n}\n\n/**\n * Meta information returned from the poll.\n */\ninterface Meta extends GetComponentMeta {\n  /**\n   * The entire response object.\n   */\n  response: Response | null;\n}\n```\n\n### Caching\n\nThis doesn't exist yet.\nPlease contribute a solution here until something happens.\n\nThere's a general idea of checking if the results are a collection or a resource, and then:\n\n- If collection, cache.\n- If resource,\n\n  - Is resource in cached collection?\n    - update cached resource.\n\n## Contributing\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. This project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"f555a62abb95e34fbdeecc1f580a0d2ab3da701a","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.0.0-7","_npmVersion":"6.2.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-lwsqilAdJcEwa0Er6OPNT8YgTSyfNVjGe0jH/r+YvKKRA16P7ovM8vxt0bRT3qxgagIXne3BotSIX2rIuef1tA==","shasum":"710f603b4cd34bf4e0b2943545dbdb59af6c9dba","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.0.0-7.tgz","fileCount":9,"unpackedSize":52587,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbZIm+CRA9TVsSAnZWagAAFOcQAIXlewuP+VncXLICmQ2i\nd5f6JwGP4xpLujOms+SZgIt4bmdMBmDbQ0LZ8cOpCC6soSjbXZoN1/oCMifp\nuOa+5K+Uwe1tR+jqNPbqajzcmlu39UnPh0nccfW4Vui+7vcm0U5aLo23Gi1J\nBL4u9jwGsKMdsCEPz22w/e982s+zyGWBWeyAAui6q5cqa39Dln3ZYYl0HCuy\ncr4WCtsD3kJhDmN9eqh44K8XmHZYfXeHjEH71KrxgL0BFzTRa/wiVuiNJ0iG\nbkit+6NLZ5N4ofshESz3Bo32vxTrUfhGesWytHh/5DrQqjX860gEti21+KDX\nmPXwANm1tweV4v/dyg8iw0QJDLNassbO31b+5WhA88BSGrXEtp0I7/T8MoSG\nLs9VZqlrTGIQhYPmV/tS+fkcQyKInHMsdM2QKeFgLNKKjQmPxvvbrxh4R5Sw\nvzQXs+YBKBfOkQ/R3PiGC/TVbkJp5D+QMeaSIYgVTMU9wd7sO2/dFU3P1FIc\nhn7l3flqKtFbG1RCb9VT9fzoiHEGFo/ZWDJjuJMW5LewGETVVkWxS5okHDSL\nyxn3RM4L32xC8YJSNnAEwLj3ZYGmPQAii8R9ryZaDRd6IaqN41usM1NvoOnZ\nUBomiYJnwmkJH2IRRHPGQiUbn8IALBkACUMmsDoZeEXdf3aC+EAppacUMqnX\nFqi3\r\n=O9bt\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIFSjoqKtGW95bJp0NRnMIiJBdcwt2hyNv+MX7ijiooQqAiEAvWvI0MTNclX51YNX2AXDz9bx41DzBlfWYbyxI+lRoAo="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.0.0-7_1533315517484_0.38891182267383995"},"_hasShrinkwrap":false},"4.0.0-8":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.0.0-8","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"test":"jest","watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix --project .","prettier --write","git add"]},"devDependencies":{"@types/jest":"^23.3.1","@types/nock":"^9.3.0","@types/react":"^16.4.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^4.1.2","rollup":"^0.63.5","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^22.4.6","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.8","typescript":"^2.9.2"},"dependencies":{"react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"jest":{"transform":{"^.+\\.tsx?$":"ts-jest"},"testRegex":"(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$","moduleFileExtensions":["ts","tsx","js","jsx","json","node"],"testURL":"http://localhost"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Mutations](#mutations)\n    - [Mutations API](#mutations-api)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [TypeScript Integration](#typescript-integration)\n  - [Polling](#polling)\n    - [`Poll` API](#poll-api)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a single component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider base=\"String!\" resolve={data => data} requestOptions={{}} />;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\n<Get path=\"/cats\">\n  {data => {\n    return (\n      <div>\n        <h1>Here are my cats!</h1>\n        {data.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n\n        {/* Request BASE/cats/persian */}\n        <Get path=\"/persian\">\n          {persianCats => {\n            return (\n              <div>\n                <h2>Here are my persian cats!</h2>\n                {persianCats.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n              </div>\n            );\n          }}\n        </Get>\n      </div>\n    );\n  }}\n</Get>\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each get _can_ override its parent with other props as well: including having _specific_ `requestOptions` for each `Get` if there was a valid use case.\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>Here are all my {props.animal}s!</h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>Here are all my {props.animal}s!</h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Mutations\n\n`Get` components pass mutation functions as the third argument to their children. Consider,\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n\n            {/* Will send a DELETE request to BASE/movies/:movie.id */}\n            <button\n              onClick={_ =>\n                actions\n                  .delete(movie.id)\n                  .then(returnedData => dispatch({ type: \"DELETED_MOVIE\", payload: returnedData }))\n              }\n            >\n              Delete!\n            </button>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\nThe same mutation objects exist for all HTTP verbs, including `get`, `post`, `put`, and `patch`. Methods `post`, `put`, and `patch` all expect a body as their first argument, and all mutation functions receive `requestOptions` as their optional second argument.\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### Mutations API\n\nHere are the functions passed as the second argument to children of `Get` with their signatures.\n\n```ts\ninterface Mutations<T> {\n  get: (path?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  destroy: (id?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  post: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  put: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  patch: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n}\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Polling\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll` and `Get` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### `Poll` API\n\nBelow is the full `Poll` component API.\n\n```ts\ninterface Poll<T> {\n  /**\n   * What path are we polling on?\n   */\n  path: GetComponentProps<T>[\"path\"];\n  /**\n   * A function that gets polled data, the current\n   * states, meta information, and various actions\n   * that can be executed at the poll-level.\n   */\n  children: (data: T | null, states: States<T>, actions: Actions, meta: Meta) => React.ReactNode;\n  /**\n   * How long do we wait between requests?\n   * Value in milliseconds.\n   * Defaults to 1000.\n   */\n  interval?: number;\n  /**\n   * A stop condition for the poll that expects\n   * a boolean.\n   *\n   * @param data - The data returned from the poll.\n   * @param response - The full response object. This could be useful in order to stop polling when !response.ok, for example.\n   */\n  until?: (data: T | null, response: Response | null) => boolean;\n  /**\n   * Are we going to wait to start the poll?\n   * Use this with { start, stop } actions.\n   */\n  lazy?: GetComponentProps<T>[\"lazy\"];\n  /**\n   * Should the data be transformed in any way?\n   */\n  resolve?: GetComponentProps<T>[\"resolve\"];\n  /**\n   * We can request foreign URLs with this prop.\n   */\n  base?: GetComponentProps<T>[\"base\"];\n  /**\n   * Any options to be passed to this request.\n   */\n  requestOptions?: GetComponentProps<T>[\"requestOptions\"];\n}\n\n/**\n * Actions that can be executed within the\n * component.\n */\ninterface Actions {\n  start: () => void;\n  stop: () => void;\n}\n\n/**\n * States of the current poll\n */\ninterface States<T> {\n  /**\n   * Is the component currently polling?\n   */\n  polling: boolean;\n  /**\n   * Is the initial request loading?\n   */\n  loading: boolean;\n  /**\n   * Has the poll concluded?\n   */\n  finished: boolean;\n  /**\n   * Is there an error? What is it?\n   */\n  error?: string;\n}\n\n/**\n * Meta information returned from the poll.\n */\ninterface Meta extends GetComponentMeta {\n  /**\n   * The entire response object.\n   */\n  response: Response | null;\n}\n```\n\n### Caching\n\nThis doesn't exist yet.\nPlease contribute a solution here until something happens.\n\nThere's a general idea of checking if the results are a collection or a resource, and then:\n\n- If collection, cache.\n- If resource,\n\n  - Is resource in cached collection?\n    - update cached resource.\n\n## Contributing\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. This project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"8fa3ed2158ec9497c6b7ac43752d99ae003e9df7","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.0.0-8","_npmVersion":"6.2.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-ienq8Jwtrj2RuFLzArALHeshNSiXtTHA3yDZJ8sSJP8iXcctY37PYAAvREmWAqn2l0Aw7OMmbK3X8FMYNZsDxg==","shasum":"0d8d36e9d24b0d2a75eb5b63152ca870f5f8f1d3","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.0.0-8.tgz","fileCount":10,"unpackedSize":53811,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbaFLYCRA9TVsSAnZWagAAz3oQAIPV3WcgED+iaSy6DTAB\nYR1vBO8gJ3kdx83cVK7nTuXqbXFE9crWZeiND7Nq2vJjfuAIggaQ230bj6hw\nIb5Ii54I+8fYHyTNNdGwVKbRAB2n2u0N6awibrg0Zb8xZ0KtkSqtxiirl17b\ndBvUpGwfHCAu4Qz5lFJfFxBYpoyrYNYanhCm2JTXCTueD9BMy5+ZPh1sidIz\n1M+W627P9VOZZJpRJtY8o4scgrfdXP1Y0w/sfuKi49tv0ezlqaRs7Gp4pW7R\n0K+oTqXRunC2SrVbnz9BZIX5hp9Nse2eMyRXhQgT2Hjs3pI/L0r6DMJWZTy0\nBI6RXR5Y1ofVJYY1HgW134qC3DbELzQvXbA+vlR5rwv/mH6GZpKi4BUPfj+m\ncDbeHyiPenAWGnTeMIUXKynAEBeo8GsjSkjJevKc7jGq7Hv5A5e9JsIPJQZF\nRzngp7cKXpfRQqFJzv1AW7rknPhJy1CR08Ne8NIsv+mvGGiS/IVt7tzxy6wj\nCbtY6hcy+yMXy/e/NKLpZtcWf4r57mg5KZznJmr9STkS/A9UuRXa4XacKTvs\nQ4WYuNcAWITwYotE3yWjELSphpNYxXfFj9GlaY1KIQhFmYBwm7ATZFRs0rNK\npaEdpNSBIdlyENIo/Ka3TOue3heA0sq+Bepwa1VvPvl166AYQu9xUMhfvhNN\nVNmW\r\n=SG4I\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIGM/q8jIeS2PzkfAizi/f0xgk2EUILTMLNqT6d80EPBiAiBrdjs8ctDdFN/z7mNbtIQI+s+l61uv0eYfx5rfgYI4pg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.0.0-8_1533563607683_0.7298434712175657"},"_hasShrinkwrap":false},"4.0.0-9":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.0.0-9","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"test":"jest","watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix --project .","prettier --write","git add"]},"devDependencies":{"@types/jest":"^23.3.1","@types/nock":"^9.3.0","@types/react":"^16.4.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^4.1.2","rollup":"^0.63.5","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^22.4.6","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.8","typescript":"^2.9.2"},"dependencies":{"react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"jest":{"transform":{"^.+\\.tsx?$":"ts-jest"},"testRegex":"(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$","moduleFileExtensions":["ts","tsx","js","jsx","json","node"],"testURL":"http://localhost"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Mutations](#mutations)\n    - [Mutations API](#mutations-api)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [TypeScript Integration](#typescript-integration)\n  - [Polling](#polling)\n    - [`Poll` API](#poll-api)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a single component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider base=\"String!\" resolve={data => data} requestOptions={{}} />;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\n<Get path=\"/cats\">\n  {data => {\n    return (\n      <div>\n        <h1>Here are my cats!</h1>\n        {data.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n\n        {/* Request BASE/cats/persian */}\n        <Get path=\"/persian\">\n          {persianCats => {\n            return (\n              <div>\n                <h2>Here are my persian cats!</h2>\n                {persianCats.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n              </div>\n            );\n          }}\n        </Get>\n      </div>\n    );\n  }}\n</Get>\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each get _can_ override its parent with other props as well: including having _specific_ `requestOptions` for each `Get` if there was a valid use case.\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>Here are all my {props.animal}s!</h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>Here are all my {props.animal}s!</h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Mutations\n\n`Get` components pass mutation functions as the third argument to their children. Consider,\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n\n            {/* Will send a DELETE request to BASE/movies/:movie.id */}\n            <button\n              onClick={_ =>\n                actions\n                  .delete(movie.id)\n                  .then(returnedData => dispatch({ type: \"DELETED_MOVIE\", payload: returnedData }))\n              }\n            >\n              Delete!\n            </button>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\nThe same mutation objects exist for all HTTP verbs, including `get`, `post`, `put`, and `patch`. Methods `post`, `put`, and `patch` all expect a body as their first argument, and all mutation functions receive `requestOptions` as their optional second argument.\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### Mutations API\n\nHere are the functions passed as the second argument to children of `Get` with their signatures.\n\n```ts\ninterface Mutations<T> {\n  get: (path?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  destroy: (id?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  post: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  put: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  patch: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n}\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Polling\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll` and `Get` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### `Poll` API\n\nBelow is the full `Poll` component API.\n\n```ts\ninterface Poll<T> {\n  /**\n   * What path are we polling on?\n   */\n  path: GetComponentProps<T>[\"path\"];\n  /**\n   * A function that gets polled data, the current\n   * states, meta information, and various actions\n   * that can be executed at the poll-level.\n   */\n  children: (data: T | null, states: States<T>, actions: Actions, meta: Meta) => React.ReactNode;\n  /**\n   * How long do we wait between requests?\n   * Value in milliseconds.\n   * Defaults to 1000.\n   */\n  interval?: number;\n  /**\n   * A stop condition for the poll that expects\n   * a boolean.\n   *\n   * @param data - The data returned from the poll.\n   * @param response - The full response object. This could be useful in order to stop polling when !response.ok, for example.\n   */\n  until?: (data: T | null, response: Response | null) => boolean;\n  /**\n   * Are we going to wait to start the poll?\n   * Use this with { start, stop } actions.\n   */\n  lazy?: GetComponentProps<T>[\"lazy\"];\n  /**\n   * Should the data be transformed in any way?\n   */\n  resolve?: GetComponentProps<T>[\"resolve\"];\n  /**\n   * We can request foreign URLs with this prop.\n   */\n  base?: GetComponentProps<T>[\"base\"];\n  /**\n   * Any options to be passed to this request.\n   */\n  requestOptions?: GetComponentProps<T>[\"requestOptions\"];\n}\n\n/**\n * Actions that can be executed within the\n * component.\n */\ninterface Actions {\n  start: () => void;\n  stop: () => void;\n}\n\n/**\n * States of the current poll\n */\ninterface States<T> {\n  /**\n   * Is the component currently polling?\n   */\n  polling: boolean;\n  /**\n   * Is the initial request loading?\n   */\n  loading: boolean;\n  /**\n   * Has the poll concluded?\n   */\n  finished: boolean;\n  /**\n   * Is there an error? What is it?\n   */\n  error?: string;\n}\n\n/**\n * Meta information returned from the poll.\n */\ninterface Meta extends GetComponentMeta {\n  /**\n   * The entire response object.\n   */\n  response: Response | null;\n}\n```\n\n### Caching\n\nThis doesn't exist yet.\nPlease contribute a solution here until something happens.\n\nThere's a general idea of checking if the results are a collection or a resource, and then:\n\n- If collection, cache.\n- If resource,\n\n  - Is resource in cached collection?\n    - update cached resource.\n\n## Contributing\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. This project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"77962dfcb1048c77eb3f5d8ceae3e5b13d545c4f","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.0.0-9","_npmVersion":"6.3.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-auQzpChtXu8bqBHNxxY9uJbjmS0vB7TuMw3+xEiBA7BuWIm2eDRpULX+ELS0cSI4DtHPLppDCHdFk3hsFmaGxw==","shasum":"8f744df60fa23bf8228d0c998524436f4a0177ee","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.0.0-9.tgz","fileCount":11,"unpackedSize":53744,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbaqhMCRA9TVsSAnZWagAA55QP/0IghkntYiN3+uiZjAKb\nXZyTUiL9XMZ6itoFdNZYIzU0RsKqmLNC9diPAoIGLnhF35NXTj5C8fbZGq68\nj52NQFiT9mythlCxPoScUPwJGU06GxdJLcTf3gov6RH2xbUebfOaJgMoQ3il\nQJTsjb4HZ9xTdGZ++2W+G3nyjhys6GsljVfdt0Z9RLkOs2vSSgaEP9O1LT6D\n+YWq+YI7KkAg+VHooOTVJ5g/oRwPdlhbSJRgs5QWLqVIzbkynbkS7IHFdRhW\nreRshEsTI12xHd1cmwH6qwKXVHyvRVGqJ0yioW4EVGJdnZ9JA5feugkMz7si\ns7+In/hoFfdYejDHMPDM3d4Y9Pc+f+5dZ8hCSm54B+Kk9vAiOhc1oF6I9OFF\nx7XFbDpmB10jMmWl8XUNHE8s9aVFLAgnoldx7p47NBsutrHsCrgM5hoyIqYG\nHJKLDmuky1FC2ZakuH0gCMNMbg0L48X+zdwb4dQvSzYGLLTdQhObT8b7YydA\nZVzF/zY3f18TRQD84MKFlE3NQQmKh2em0rVBVikQasHq20X8lhlyUnHr+Igr\noohDXeLx2p8lbDyI5cCTTAAwLW1AvphOVeV7nD6UxnNh4qjh1s7ggY01vMh6\n3cq0g/5d8rRZ5oICuuS9z1Db86NQ8+dO9Tb/+/TwpuxfWYOQJ+REVQQEzK7O\nMI6c\r\n=ZbDk\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIENR4m1kYJhTcmRWhJoK8dxfWQMEBvBTQsendGO/Hj7aAiEAmyvO/XSY1IO8PumfQ+jDLpFuVrWR6sMF5IHoswoTPqU="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.0.0-9_1533716556553_0.8992023148327597"},"_hasShrinkwrap":false},"4.0.0-10":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.0.0-10","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"test":"jest","watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix --project .","prettier --write","git add"]},"devDependencies":{"@types/jest":"^23.3.1","@types/nock":"^9.3.0","@types/react":"^16.4.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^4.1.2","rollup":"^0.63.5","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^22.4.6","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.8","typescript":"^2.9.2"},"dependencies":{"react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"jest":{"transform":{"^.+\\.tsx?$":"ts-jest"},"testRegex":"(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$","moduleFileExtensions":["ts","tsx","js","jsx","json","node"],"testURL":"http://localhost"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Mutations](#mutations)\n    - [Mutations API](#mutations-api)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [TypeScript Integration](#typescript-integration)\n  - [Polling](#polling)\n    - [`Poll` API](#poll-api)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a single component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider base=\"String!\" resolve={data => data} requestOptions={{}} />;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\n<Get path=\"/cats\">\n  {data => {\n    return (\n      <div>\n        <h1>Here are my cats!</h1>\n        {data.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n\n        {/* Request BASE/cats/persian */}\n        <Get path=\"/persian\">\n          {persianCats => {\n            return (\n              <div>\n                <h2>Here are my persian cats!</h2>\n                {persianCats.map(cat => <img alt={cat.name} src={cat.photoUrl} />)}\n              </div>\n            );\n          }}\n        </Get>\n      </div>\n    );\n  }}\n</Get>\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each get _can_ override its parent with other props as well: including having _specific_ `requestOptions` for each `Get` if there was a valid use case.\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>Here are all my {props.animal}s!</h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>Here are all my {props.animal}s!</h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Mutations\n\n`Get` components pass mutation functions as the third argument to their children. Consider,\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n\n            {/* Will send a DELETE request to BASE/movies/:movie.id */}\n            <button\n              onClick={_ =>\n                actions\n                  .delete(movie.id)\n                  .then(returnedData => dispatch({ type: \"DELETED_MOVIE\", payload: returnedData }))\n              }\n            >\n              Delete!\n            </button>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\nThe same mutation objects exist for all HTTP verbs, including `get`, `post`, `put`, and `patch`. Methods `post`, `put`, and `patch` all expect a body as their first argument, and all mutation functions receive `requestOptions` as their optional second argument.\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### Mutations API\n\nHere are the functions passed as the second argument to children of `Get` with their signatures.\n\n```ts\ninterface Mutations<T> {\n  get: (path?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  destroy: (id?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  post: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  put: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n  patch: (data?: string, requestOptions?: Partial<RequestInit>) => Promise<T | null>;\n}\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Polling\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll` and `Get` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### `Poll` API\n\nBelow is the full `Poll` component API.\n\n```ts\ninterface Poll<T> {\n  /**\n   * What path are we polling on?\n   */\n  path: GetComponentProps<T>[\"path\"];\n  /**\n   * A function that gets polled data, the current\n   * states, meta information, and various actions\n   * that can be executed at the poll-level.\n   */\n  children: (data: T | null, states: States<T>, actions: Actions, meta: Meta) => React.ReactNode;\n  /**\n   * How long do we wait between requests?\n   * Value in milliseconds.\n   * Defaults to 1000.\n   */\n  interval?: number;\n  /**\n   * A stop condition for the poll that expects\n   * a boolean.\n   *\n   * @param data - The data returned from the poll.\n   * @param response - The full response object. This could be useful in order to stop polling when !response.ok, for example.\n   */\n  until?: (data: T | null, response: Response | null) => boolean;\n  /**\n   * Are we going to wait to start the poll?\n   * Use this with { start, stop } actions.\n   */\n  lazy?: GetComponentProps<T>[\"lazy\"];\n  /**\n   * Should the data be transformed in any way?\n   */\n  resolve?: GetComponentProps<T>[\"resolve\"];\n  /**\n   * We can request foreign URLs with this prop.\n   */\n  base?: GetComponentProps<T>[\"base\"];\n  /**\n   * Any options to be passed to this request.\n   */\n  requestOptions?: GetComponentProps<T>[\"requestOptions\"];\n}\n\n/**\n * Actions that can be executed within the\n * component.\n */\ninterface Actions {\n  start: () => void;\n  stop: () => void;\n}\n\n/**\n * States of the current poll\n */\ninterface States<T> {\n  /**\n   * Is the component currently polling?\n   */\n  polling: boolean;\n  /**\n   * Is the initial request loading?\n   */\n  loading: boolean;\n  /**\n   * Has the poll concluded?\n   */\n  finished: boolean;\n  /**\n   * Is there an error? What is it?\n   */\n  error?: string;\n}\n\n/**\n * Meta information returned from the poll.\n */\ninterface Meta extends GetComponentMeta {\n  /**\n   * The entire response object.\n   */\n  response: Response | null;\n}\n```\n\n### Caching\n\nThis doesn't exist yet.\nPlease contribute a solution here until something happens.\n\nThere's a general idea of checking if the results are a collection or a resource, and then:\n\n- If collection, cache.\n- If resource,\n\n  - Is resource in cached collection?\n    - update cached resource.\n\n## Contributing\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. This project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"f39211654abb19543fe31857880662b5d1ef8efd","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.0.0-10","_npmVersion":"6.3.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-guqVBGr73NTXR7Erax+k/wESiHj/JhRo36HV4pzSoFudYGIM25JLcoxJcH74WF0T7dtkNWrOz768qV5hZKoCwQ==","shasum":"08d6f48e5de1e586dc52d6f4ea98dbdec470427b","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.0.0-10.tgz","fileCount":12,"unpackedSize":53163,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbavGACRA9TVsSAnZWagAAHskP/0VEPDLroEwq7fN27Qzo\nE3JOyb0dCp22vrLUQcdg9Hu4JKtlnRXQbohH85vrIdyzvq/LHqf9QPwVXbwI\nLYeGzf+Hf9tyaq6+uAkM/ipA1Q+qEr4+tqXchLKO7w32QdH++rVlybj/v+1F\nwfuJRJH1OmrOHbXzhASNWDDW3KcQG2wdwXxy0D7XrRNDLLQ4vlc4KORO+KwS\nU17QKt0Yjpl33prj+mgIqOWyXz2d9ExT/CqWn7l24EceueQgwYcedlim17lB\nrVH+BdNObpW1vHxhgWogHgl48phctGNIuhoRfTVL3LNuyMxc7CRz2PDt4pSI\nn1m2L0BMEKuKBlggRzKE8Q+eLWopzfipCfw3Opk9RyKBqkeRMDLXQLYJolSM\n/qnJLfRLJAWkqUVicRpN6KWrfUGMu/kl8/dG7G3TiLywcgIUImdgdLNJ/ITm\nfCJ1a8zjGNvpx/KVl20poNFK+rB+eT1YUUX8ji4neyvzELJG/LSUek5gY4+K\n/txc70duTRhgAfVHqdonyexIfiJG2eUyId8pUvokWD4PxReRWMEYGQFod1B7\n/A4ZXzFfjN6CH5NwtlU/KNqvx0L64CON1Wxfp+ZIBOaX7nQq85Az3IlVdKcz\na3A+2rA6Bjpf96ECucWf9SWE0GU3HF0hUPnA8aXsWA2D5DsOBsvW8Z7busx6\nRAfu\r\n=SUWR\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICB5LjCgxa61UFKIk/UMETAl4fPGAFmbeJmeLUWL2T0mAiEAxqKmVU1s/z0REF2US9N0RBKXW9g5OqSYUM8XtR+ECt8="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.0.0-10_1533735296232_0.07208227013707202"},"_hasShrinkwrap":false},"4.0.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.0.0","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"test":"jest","watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix --project .","prettier --write","git add"]},"devDependencies":{"@types/jest":"^23.3.1","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^4.1.2","rollup":"^0.63.5","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^22.4.6","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.8","typescript":"^2.9.2"},"dependencies":{"react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"jest":{"transform":{"^.+\\.tsx?$":"ts-jest"},"testRegex":"(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$","moduleFileExtensions":["ts","tsx","js","jsx","json","node"],"testURL":"http://localhost"},"gitHead":"6f1b79c6c966018405a20f82cbcf33d9f7c62b99","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.0.0","_npmVersion":"6.3.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-gLgjQ9d5zQL08v8Hdcu+Xa/sdw8IjuCBeEmEOCJRoJYnjk4b7msUf2ExOORa4+V8yKn+blyw6vvCd3NGHLFx4g==","shasum":"7ffd7df9026853eab2d6ddc6d7bd6d02db6f2b1e","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.0.0.tgz","fileCount":13,"unpackedSize":57001,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbav6nCRA9TVsSAnZWagAAB1cP/iy5YhEgz78zs5FSoyh0\nkB5eQEJuHWPS0EYYQTq8Tt+hY/TmDL6/4rq7h2Qrpn5IItXwQBIhYhr4uAjV\nKV96rgoonzA/nFgulNfRK84Etz2N/g1cQKHkM5j5LI0tGaPtMi7Pji1Aav7x\niRUvjbW5v26HPoLF01AuJk8Np1AsZMpVtYwgWUleo+XspzAF+5Px44SVXhUq\nFhrsiI1ezsFF6zmKKsetD3/sYqoxQnOAsrHoGy4xBtHHJttd1ZE03KreFw4c\noXLh9iYCbty9wwWfvpvWWMLQYxSUaiyZngcSiwD4yuderFsIB5EL0drG86UW\nbZHt7s3uyLz2vWIhKJMc118idbmCKgQJtLn5wco0pZ2z37bIGfgNbo5Dc70m\n1TdT+E2Wc98e+7vn9BLvlA+OJcc22H3CHe1kK4a+/hPbMwN75JeOXhkn9YnF\nCPZNa45Eh2fKAjMS6F0UWzzbcbc3mxxczxeBe6Pm8gmKwQRNm6H6yrKknpGJ\nV7Vo9yBsR5D8JcWwAwONbk8OKKrng62rVSQONoYIapGSoAnVFEUeaVETzZ+t\nj+kGYF9Wjor3qvNJTHvMdcSvf8IaUxQoptRIpfVe0aL8LywqjuKhaEhp3i62\nfIr3VLMQXqY88Sd3Vz9mJ/vbabUPfVgO4p2HRWGgY87YXqPMSaPxtPMVf5ut\nyZVR\r\n=w5r7\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIHoUk9z7oLOzs3DGd0h1sb/Uru6xZdW5rQo0kjHSzNZDAiEA8zRAnNY3ZyJJZf4MJvw/0f6BCpnIU2cl3YDJaTgwFiY="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.0.0_1533738653176_0.4715665720482798"},"_hasShrinkwrap":false},"4.0.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.0.1","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"test":"jest","watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","ci":"npm run jest && npm run lint","jest":"jest --outputFile test-results.json --json"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix --project .","prettier --write","git add"]},"devDependencies":{"@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^3.8.4","danger-plugin-jest":"^1.1.0","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^4.1.2","rollup":"^0.63.5","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^22.4.6","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.8","typescript":"^2.9.2"},"dependencies":{"lodash":"^4.17.10","react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"jest":{"transform":{"^.+\\.tsx?$":"ts-jest"},"testRegex":"(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$","moduleFileExtensions":["ts","tsx","js","jsx","json","node"],"testURL":"http://localhost"},"gitHead":"f80039587cb2971d310542795d1a86536ea6a87e","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.0.1","_npmVersion":"6.3.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-B1dPtaqPEeaB58h++Ven+vJCOUFc1iDvvqzBI+zdEROjHNHXqqkUfhawwp+ZSMDqQxXjttndq44b2nRvFnoZNg==","shasum":"b69cfce9ac4f0deb816a9369a5c129c1c1b8560c","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.0.1.tgz","fileCount":22,"unpackedSize":69180,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbcp0HCRA9TVsSAnZWagAAUgkP/0vRB1LSwL6s2U5XWtgN\n/iZPYsteceVQQW0R9THy+AaGq0GubnbKwoC0zG/MPNsDi9tnSnAjZO4+feeb\nspx2EMhbDrrFbdJq+5m+hmeBCtB4d+F9/5YoEL0vAN07L9G51n49zriMp5NH\nk2Va8FHBgb+UrnT1+0PV5rUcuE98i6rJCcpZuSZ4n/4nd4IBrEQyhW2R218C\ntBRgDCY9Wf91OzEYEcRenHrn1K7gRQPNcdaAhZLqvZdhXRix2q8kWw1LsVvU\no6y5NWH413wKnc9v+edBTDtArek0e7pdNCnXu87/y4eMG9MOfGj0pRlx3UA6\nxpGH2nhEVQ52UwKPs0U6SP+kMhk9iuK6iJar6obBtCsyuMaJU+K5Vh11ysJR\nc2SzaaLaJvvrIlUOhcGL3ZlX9wtdWSeVLTPwEL+RYfRz7QysOdAs0Ih3k9xT\nd2a6kh/6fq5pFDutKnbt+l+qgocmtZY3bMM0Igtbeo5SLBJW1phnZ+MW5HmG\nNRg6GpUnUqgsWyjkAPAL43p12yULlrnJvSZWD9/9tbGApchpOGVbJVk6OMho\nsW34VXnSA5fyqDSAB/G2nwswS1mzYgPPnJTjmYljGPkbuSdx6jAN5hi0Bg7m\nWIgF2flabmyclklFhGbmwNy9D/nRxBJeBv3BN//DjlyZ+iE1LImbk6oK+Nvv\nmmBT\r\n=0o6g\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIFj4YKI4Rh1Xx8b3l/2Rw7NwzGn/ajeaN2TNZlgWCBqbAiEAlpDk5mbEi3e+w38n5LTpLguu+/qb26HJlm7JnTse/54="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.0.1_1534237959002_0.6969680197643311"},"_hasShrinkwrap":false},"4.0.2":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.0.2","main":"dist/index.js","license":"MIT","files":["dist"],"engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"test":"jest","watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","ci":"npm run jest && npm run lint","jest":"jest --outputFile test-results.json --json"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix --project .","prettier --write","git add"]},"devDependencies":{"@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^3.8.4","danger-plugin-jest":"^1.1.0","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^4.1.2","rollup":"^0.63.5","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^22.4.6","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.8","typescript":"^2.9.2"},"dependencies":{"lodash":"^4.17.10","react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"jest":{"transform":{"^.+\\.tsx?$":"ts-jest"},"testRegex":"(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$","moduleFileExtensions":["ts","tsx","js","jsx","json","node"],"testURL":"http://localhost"},"gitHead":"56b011327c09d86f7deb6e8f1a27b5a0b64daeda","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.0.2","_npmVersion":"6.4.0","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-BuPf+QdRLLh3+sG01k2+uBSQ5yeXE5MrKGwcZV9qtiomrg4tnQMd/q9Hd8tJwDQp33yAVpx4BdyJPhiASbFaMg==","shasum":"46ef9a99943806475979c3a92cc0a4c582e76cf3","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.0.2.tgz","fileCount":22,"unpackedSize":69510,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbg/zeCRA9TVsSAnZWagAAuAMQAKM81k7mpjbK0kx9GABb\nMMiR3woFgc0EXQv9TzgLU8Ofc8DPkff7GL2EDlXPwtfG+XM7IfAbcDytAZCB\nXTD5ibFv/8kXXdlfzeN5GiMmhzwqTUPdxytaVb+CYJJPrs1DcRBIQlMuJMmG\norw4eajRN8lHRLxObb4HvW+qXz7jRJ1L7KPS1hW0xfcn6Wevfemw+FaqtQnF\n4ThiLCPiVG4R2bs2R6EjPRDZbhtmZlduY9tybeK4bKgXsqHSUvbn8ilD8O1l\nXeWE+WZ66zQis35wsl9rQrjn8u8sSDm1h8BvLP6ZiTq0ffiezNDRW356U2hA\nYIO+m3Hc5ZD4q0q4v/Xj7V9uPFMwXfOsR0ijMvVjmF7Ex0bp1fCKxshaob8E\nrUEE3OSMsIhRPV9vSIP7zr0oaUrExj3+GNmNsseCQ6FCoJLM5Z90GyZ2Fhow\nP1xxvtfm8f1tEOq6G15C73npnQ0Z/umSAcMXP5nKfoC0fIoI2BBGbTgXQSsu\ndWT03lLsM89vxF4bd4knEl/X5VBAfgGTVcxHsHvqXLIZlJpI+ofMEl35N6N8\nOOkutZp83bvM50Ar4todMIO6i6+fVsFo4lvyF38zncBt/G1apaEapQKe4I94\nHoZVPtr5hLXI36X4G7WiggNpktNbYJrSs2ZADgYjcAppP2W3dGfdxxPM9FZ5\nKxTB\r\n=751w\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDDVCiT3GNWRbZb7p7T1ym6EF7C+BoUD1TIwKzEE1+OPgIhAOkBGi4gWaVydIZCCPK5wx8pO6HaEh5qQlOkeT1RrrFt"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.0.2_1535376605960_0.9941739822072346"},"_hasShrinkwrap":false},"4.1.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.1.0","main":"dist/index.js","license":"MIT","engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"test":"jest","watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","ci":"npm run jest && npm run lint","jest":"jest --outputFile test-results.json --json"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix --project .","prettier --write","git add"]},"devDependencies":{"@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^3.8.4","danger-plugin-jest":"^1.1.0","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","rollup":"^0.65.0","rollup-plugin-typescript2":"^0.17.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.8","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.10","react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"jest":{"transform":{"^.+\\.tsx?$":"ts-jest"},"testRegex":"(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$","moduleFileExtensions":["ts","tsx","js","jsx","json","node"],"testURL":"http://localhost"},"gitHead":"d56bd5f46ccf2f915199cfb3d98e3390b395b6f8","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.1.0","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-PEGcTT7dHveq1E4qNj0Dq+muoyfx9n3Fff6JFotXl7hDhPzlrTBQ+UAyZpFKKP7e06v6iCImOaNr8YhF+S1jBg==","shasum":"b33300e827a6d6d7e42f71dca6813a6e27b9bb8b","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.1.0.tgz","fileCount":22,"unpackedSize":74435,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbj5lYCRA9TVsSAnZWagAAMUIQAI2IBlwwff0qrE+iPt3e\nIcloJK1ogIZVoNzzCTuwCT49Wv0mUV065DEI8oPbW6axmFlUWS3GY8gXbMp+\nx5f2dnYVHX3c4pCiswZooWGEGRc81dSXd+ZBTlT0c0Yt8+4YXNBoGMulAiwq\nvomfJ9RmeZIFFOmpmTtT6NqVWKOfH2BoR5a809C2tDwmtFNH76jBZSzV8AmH\nJSHv5CmgxoDXdCVu9ghIz6xLbUTM1S6piB5CmQry7AMqSZG6Lv3wTAr3MCfb\nEkSxtEDMrhln1EWXV9glHWwLpmVvPEC6M5CIjZllWz6NrXjN2+PefETq91Ec\nNs1RXObqAZOokpO33qCbVe6Z02N57mtIW8XENCpJ0WqVwKYyJPVWG4VvLGVz\nxhRWEuGM1oCfOkPrIv8PU37oJmfw7Dzh2WigTFWkmoW9V9VIiViL/etQi1JM\neK++ZpKY6zWhWtH2uMS3LL60XMs7Jr0QMdmMGXmGrl48uhwtQ+u2Q1Q+fTEz\nGH1RXdI1akFbH+St4gve1NavjKpYOrVUQb0ZniJI6meY9pmAcySXNdJPPyqn\nYXcaKoqVgFEKCjkHO+Zf4aAEoLRMC1D8Vtkrylycnkg4TSBGS6uCP7ISdSf/\nbDwgC0xaNX0baDbIFB2rzvaXO81xJcufjPTbDTk3Xj66O2hvkzExn2bacCx2\nBp1R\r\n=htAw\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIFjHFydINg27pFX31BaZungcqSBC/JpqKlzaic7297cfAiAx3I0B7HoDbxKnzWTYKwh37ea18mZccSq4qNkmmRjREg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.1.0_1536137559557_0.6778056213735086"},"_hasShrinkwrap":false},"4.1.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.1.1","main":"dist/index.js","license":"MIT","engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"test":"jest","watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","ci":"npm run jest && npm run lint","jest":"jest --outputFile test-results.json --json"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix --project .","prettier --write","git add"]},"devDependencies":{"@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^3.8.4","danger-plugin-jest":"^1.1.0","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","rollup":"^0.65.0","rollup-plugin-typescript2":"^0.17.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.8","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.10","react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"jest":{"transform":{"^.+\\.tsx?$":"ts-jest"},"testRegex":"(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$","moduleFileExtensions":["ts","tsx","js","jsx","json","node"],"testURL":"http://localhost"},"gitHead":"0cafae7f535f5308262c6741e08d3d0d83de2f73","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.1.1","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-4aL55WRkOeSwdU8zwtLangcvk5PKh64jw5oOA6m31aGBaX5PhoWeF5UAtCJCilxZdb+k/TqKlrhE+ffoJq80vA==","shasum":"1d22947b700e4f9166150fe5996cfe8455e8e921","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.1.1.tgz","fileCount":15,"unpackedSize":69583,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbj50wCRA9TVsSAnZWagAAQz8P/2E9X4VLg7cYctymCfgm\n3G836EpNthf+BeltihIka06HxMg4qA2joxseEB5Xp6C97ZJL818zBBBj2l4u\niKHiDiqot+MEXFYuc3tgud2KKR90gdxhl5mtMjLDUQZoCLxlJoF+MZZYkNIl\nepRpgBpp74knf9+qA1K0nuo0OV8FQs1bXNiqBpq5U7d4fzVV8ITqjeBp2k+Z\nr5z8q2Ujg1JvF3lOijsyxVu0U4s/c40dzBGqyYCl4j7fPu8gBODWilzeIdYr\nEk+kiTfH/zo+1khffudiIjp1pF9JhjHDrFT8ebP3T31352jFEUuSw7w/LGJd\nax/Lj1m7KTEWv4fvpfWwt3dc/tNk2j7vtnRY/PF4O5px6jNsGmkGRDRSvR3D\nZyszLNOkceAOAH3IcfdO+M6YRKb3mTyE23UxZD/ABp8pT9Ru39M5E5B5FoVj\n6z3SdTrUaEyOhHU1UK1Jb9aG7Tps68p2NNmjCdN5tD/sgAIg++90kS8qn2eN\nH7noJEbVOTBZUmNdkJ795mCAfrIW+cQacw13oZdexfbV3ub76ycL1VeXUgz7\nOrLIvssq6horZMlaCU0hj7PUxILYLbZLsZCOuzhq77a7s7Lp3/yx45CitaaD\nWCYBteGa4cHlCdcraaXe91tdjSEGexc8LzPZ8dFMdpCgwuBGYk3iHsaMaBIh\n/jff\r\n=MoR6\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCLoTwaf6XVFrmXg+xYC4uJ2Q5PN9lpRFBqeEdcgQhCLAIhAME7fKex6BXE+mRwJ1u15jaxMHbm2BS1IBE9GboTfLsR"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.1.1_1536138543382_0.26254304218091695"},"_hasShrinkwrap":false},"4.1.2":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.1.2","main":"dist/index.js","license":"MIT","engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"test":"jest","watch":"rollup -cw","build":"rollup -c","precommit":"lint-staged","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","ci":"npm run jest && npm run lint","jest":"jest --outputFile test-results.json --json"},"lint-staged":{"*.md":["prettier --write","doctoc","git add"],"*.json":["prettier --write","git add"],"*.(tsx|ts)":["tslint --fix --project .","prettier --write","git add"]},"devDependencies":{"@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^3.8.4","danger-plugin-jest":"^1.1.0","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","rollup":"^0.65.0","rollup-plugin-typescript2":"^0.17.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.8","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.10","react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"jest":{"transform":{"^.+\\.tsx?$":"ts-jest"},"testRegex":"(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$","moduleFileExtensions":["ts","tsx","js","jsx","json","node"],"testURL":"http://localhost"},"gitHead":"d4ab4a1c759f92c64ea2cfc9bd694f3b463545ce","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.1.2","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-NamveJdMupquRN02GrvhDIJbRynHsOTSZhXtWI8UfPnxCzVN9lDsIUahrPU6Tf6+J6WWb5/dSnMk0+AHm6XYgw==","shasum":"0dcb1c7ea2b7fedc0d4a3dcf4917ad722c16c816","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.1.2.tgz","fileCount":21,"unpackedSize":81230,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbj6GICRA9TVsSAnZWagAAo6kP/1/R7tKsO7ELtDoFOLcg\nnri2sYWW+3Tkdkw78Y4y5qYi0NDRXEr1dJ+ZzVmLMyJRF8aH+Zkk9MZgNcFq\ng+NxEhyPmjjHBwrzXn/Qrst6nJ7mI9ccdSS9RDosSFkFmxNZSlVQZGQefDOI\neDB6MhEgsEJGLbA0+0xREQRojiBb7o+hH7lqD3y+tRIzUmPcYGUmiiTtHvBH\nitzJBE5/DsNp51MpShnnS/wbK/8laNLAmMA29k2OmzX+A3CcVShL/ORIVKTg\nAlCudS37C0lr6WwXwmgeUXQ5Nqhc/9YAfj+ul4BNNV2tDhFc3JXpkH9IcCht\ntJIwXyOhxxz+/fzRS7AbneZhIA8kdU0QVXN4GK9ggARIqTChLQKPzSSgccr7\nGsBbCsu9G9/n5kkFAyB0j55HxVBYGttpHg8rFZAvhcu7zqpv96aT/rMf5GBV\nlzRPwhRQGPY4HX/B/4htCqDuNPwvreCruFiwSVkUxJIBSAoZnHE+ttVm6+m0\niKaLdM19arfDcHJECgd/alRZBhIHkVaNjtMKZZiPpdK7zexWoIRWcHMmE1SI\n5DLqnbARGiJ8Z2S+jpuQmsCzZ1nHSoaOSKft+a5NR930zzmte0QB6X3agE0r\nQh6VDo3lu336oGtOiqAKVLyQKnQm8/ZWyFv6SQqd53yACCuzNC6OBEtZp/iM\nrfMW\r\n=SypI\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIF1FO79JasplYLfJWPKxUfllPqYT7LbcFQj2K28Lrg79AiEA5bwzVXoE2e7QNGFBmFPBs2MwwX6TQhXuARVKkTFpWDY="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.1.2_1536139655460_0.8936136569055599"},"_hasShrinkwrap":false},"4.1.3-0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.1.3-0","main":"dist/index.js","license":"MIT","engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare"},"devDependencies":{"@operational/scripts":"^1.1.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^3.8.4","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.10","react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n [![Greenkeeper badge](https://badges.greenkeeper.io/contiamo/restful-react.svg)](https://greenkeeper.io/)\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"b402e35539f059a0b4b0e6ae3e761dac78a1fc39","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.1.3-0","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-TMqJr4Ef+QaM7X3RmIv5bM2Nrq4HW7Pl4B8Wf6Jq2ljLuzDiEoF1eqt42E0hjedHPLZJA7h4YCkQnMBWE4lbjg==","shasum":"5aeb40a100de0247dc647923ca02a2208853943f","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.1.3-0.tgz","fileCount":23,"unpackedSize":118178,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJblkwyCRA9TVsSAnZWagAAF94QAI6iUVXIecOjmWNDAId3\nuzUHEjulWIVqNbXXwJWoHvBOHd1XoacZ5RWjG7qa1kEvKN/4CSVXBlmmX5gk\nUiA2G1f3WM1zvCJbjGQ/d6/T9VMpdJpipzMcp4jVtGz9Mj5ww0JqRFpWS6b4\nMlsHBKYpQDF7Vme1fGwcj/1/kWh662dENhbl8RnjiQd9QHnCafcrHnlCPOu2\nj09y2a2I7o3UuiGU003H1ntAgEfTKgIc7jKUs7TCaWOQyfSpt6T/Q5ckVDov\n8sJFkqCNhRZ9H7v9htRXpy1Dcw0/NqjaMcgCizxI1Y5UGGIO96NKEf7wTq7j\nM3WA3bV0EO/codA0klQ9INrgzarGvQJx/8BrO0aqxoUoBooRVuF6llNyd5cc\nlnLycQ5snZO4s26ESA/nIcDJ++IPn1NzBWkLo7Zg4tnBvUx/gKCtrUOCUVEc\nl1nQ41dxMcw1XGkt2+M6hLRPuiFimqFg21I+r/9JDrF1PTva3stqa1EEgzG4\nPWZcxi4GdrwOB56KvkXNWoczQPuN08UtNkfv1K++tNjzLv1Tl9Nrl7hygGSU\nJArz3E96/DGWfvqU3dIOXm2rkTpQiaBXupgePZh06tI/9nru5pNhbNZJwlMa\n9BnYdT3CNEhzUfeJRJwlz5t5GNCgmch2CFO5mrvbOqXQBjfaKlXC2VLXntkl\nPTc3\r\n=ZlgC\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIHdnJdx1V6xks3aTJE1e5q02xRhpDFpCFgNcW8COixcJAiAlsbZeG446Ji5rT6nnCD9EAyERTZqrtmkYIhLhBMcvnw=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.1.3-0_1536576561758_0.7659378715055558"},"_hasShrinkwrap":false},"4.1.3":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"4.1.3","main":"dist/index.js","license":"MIT","engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare"},"devDependencies":{"@operational/scripts":"^1.1.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^3.8.4","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.10","react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"6cf8d3886f49e69f608bbee60b0e8670100f4045","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@4.1.3","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-TiqDZ0J7gEA6A8E2Jw1dwdLJXGaAIyw0MdaXVAZZAqFo6eSPPCcicJSvwlblKH3pmU71FM+fnO4Bb9mtFEm2jw==","shasum":"9e96debf479813815340a754bdc631849853fab9","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-4.1.3.tgz","fileCount":23,"unpackedSize":119029,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJblk6zCRA9TVsSAnZWagAAqeMP/3GZrESyNWRtWfiTf1/N\nNoLGy/0TuYys2zCZtw9Yv2nHDqAEVYjDyVHO5qJ8lpi6Jhx5rQVYG42SAQUK\nAQaq1YsA3w161nXxi8zNXGagQ/AqD8V1zzQg+X+Fnl90krVebNJAls4cJumn\nlA0lDRZWoeK5hcQbRqFmsAP6BYoI/Uuy1uW+vKDRpXlt5+/bvlfNg7XWnL2u\nRbAWvWSmxZBiWx70UUgikEQYUXEi3HWCgVrU/YX9Upi20DC7G0+g27mpkzkz\nC85KBhpJBrperfqOJrA0VTSuXeN1xjdtUWAurlNSn79B85P8BBbwknQs8g33\nt4c2V46NfyAXKrfFBPdvQRLlbe1iNRsK47wOTgw9WUChetxPNITwTFNIZAWj\n35eujTgm5cqegIDg5yZTeFvW4ELhoPBiuE5dy2DEGdqzIX3TNDcu5FndGQs8\noC0+fGBUG+eGNIE84wgp4sZgedT/XPTuSsgqaXmo0Yy4a9FXwVuDIXW2Sfk1\nCW/iBgtsIR6rA6oDe27LcMopFKoLiqUXF6CcMS/qVPcZsko8H084RNEakOsa\n/xcakPvxc+tN4QBYQdo0cMjZTXWzms+umXYr01m+9ajEcRbAQCTukjugEEuA\nzWgW7mUIn9qA1LDCbgSACJSghe2ivJNOewGjZDsf/B0yEFHr0d8jEuSnvBi/\nMLUU\r\n=Vc6w\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIF8nvB2KmVtKpvvDUJrqkgZoFxIzSOWfuIUJb4UXjSLGAiAEi1AIvQ08CSMK3fAbWlP8PfDnYytU5tFKj0a3p7VJfg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_4.1.3_1536577202302_0.5537180899764216"},"_hasShrinkwrap":false},"5.0.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"5.0.0","main":"lib/index.js","license":"MIT","engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare"},"devDependencies":{"@operational/scripts":"^1.1.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^3.8.4","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.10","react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"be1f60691bfcaf1eda339a37703cbf7dc96f3da6","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@5.0.0","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-89PSg+T6fZMckuppx/2pa6mD7m69FnQvAsjWIYQp8QOMbmJVtK9Mzv2VY+IwuaXO+xQ+0xeph8HWZxkpvyPr2A==","shasum":"db23b6cbafb2784db0247d6d191c44467402725f","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-5.0.0.tgz","fileCount":22,"unpackedSize":94065,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJblluXCRA9TVsSAnZWagAAMoUP/2KAJdxDDrGgweUPdzw7\ncHF8sZsUP13e2iQQOnK5/Nuha9xLLBnnH6KaM/QNPLPAJ1IYTC3na364Xyt/\naw9LyjTFEJTBkRMP1+P+ynXyRFnTeC/uvaoNkXzh4NB4ZM0GNtsj+RmYVO7H\n+E9Dd7JXDi9AWuZCLtnKuMnw32iU2oEzf7d/fo1mN4DfUG8Ch6vQM4qoBduB\nbVpJf7gv30RhrC+xrawuG8SpSt7ZUoDNdW4JbHCmss7g2dMEi90genPUWY1n\niOwv+N6C83VqcVTk7TaPI+wLw8Crn5kFi0kjBgKzPscVP+YT3rXQgslsZ53Z\nqHWVPx2okmBnsXEbE2TPi7nOZM/OkAVv8WkjI0/YCcx67NkyXshBblHxbUZ2\ns8UiWO4l4IADqL5VCOKYJ3scPJwL2RQ50sWJ0YEZpZzj5yqwxzZ0+EE8yBbS\n2W738d4Jxu3U7cN+qHj05n/N/pyMWpN3+EUA5hnUm+nwdFD3QBdyEAfjM2CF\nFVapt5qNKqgqW4GInB3oYCNkmhA2N7j5JGPGuU3EkxhC5+V4HIqDxqgzRTdT\nO4R6TkMYX+Wbh6pN3g81rZ+TtSPjIyv9bUdOYJVGf92AARmUaPOBn5RYs8ij\n13wBqeVZTS2UaLl+TH8Aq6N16PKUARV1x9TklWjMkLB3hG7qIrT6QV2XQv51\nkTjL\r\n=cyNg\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICou5yW3uv0gvVyXsvZ3tJTYxODyAns8bpWO2IhQp/1SAiBk4YDaS8VP7zOspOR3MK/+Iq89up9CCpOlvs5pFiizPA=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_5.0.0_1536580502508_0.13739836469164324"},"_hasShrinkwrap":false},"5.0.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"5.0.1","main":"lib/index.js","license":"MIT","engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare"},"devDependencies":{"@operational/scripts":"^1.1.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^3.8.4","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.10","react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"d2efd1f676eed8ba85701b51a5f60d232bbab676","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@5.0.1","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-UxdpgVSYg4fYBMsrFA4ZNCXRhaSZUrxz/cViCMr7bz5TYiEZT6FZfpNlPGrbk/jpLvlaU8H9u9hVLNn4ScLY9g==","shasum":"bb63fc0435c5e3793d8c9b05ca0afee2658e92ac","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-5.0.1.tgz","fileCount":22,"unpackedSize":94327,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJblnq9CRA9TVsSAnZWagAAi2sP/irqB1fI0Qgsa4r8cGj0\nd7dBGcJM0eqzY4efRPyDntqP3Wa5KrKMLlwcL4LzD70rhNro1gCpRbbR77rz\nRIgvbxE4iOtM0ZMYMushsrNGIsrhg3FXpxaYhOOP+jUwBp/DfoRNhJWhFM/Z\nmNORrqzQBfM5rKcl72x7vuI0wxpgH8e/bemuXJp4mfZSCUUIMj6cVN6DicV6\nhMnF5ov3THGdPuMRAMXlSGRLyMvT6giPYUgT+v9k0uptoGcCF2QnuHm1yQOt\nQMXpWkiBc64yWiGc+D8IWhK0FrSAtGVsl0eoPq/DoPR5721sm/ericORJYdg\nkZZTfgbjGdNk9xUvEsOecff2B10HdGnm+H3xmmGMxdU3CzhIn8+9iYLzPrKt\nIo1obSrYLCNJgGiGosaugUfH3xVQNdXrmGMAP5avpRJ+IYBADd7ltCu//Boz\nWUkeV7dUQOFWBLgSknaQF4tMFZ0hfiYELxVUQygbexDNierRWXJcuVoRIfuS\nnRH9VH3g6J0mqoOw7zSc1x8o2V1lSwHNG17Pp6eZeNllgQNLf++vzbNvVdcL\n/FhmDzoAz8aeFysozmw52bSMW+B7nPTGavlPlXwUEoH6ZP6wdFh1SzHQeCUc\nd+49qbWdrkVnTi961BRQZpMI3PP0+g/AaIPihPIsED/xNJsgCP5MgkCQxECp\nyI8u\r\n=2jCQ\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDs24mg8kwpFeaT1m9V8XzAS3Z0+Ym/VujTpILcCauA8QIgVVx7e/I6hC9o+G4VkFRQ8iuPFrhSyW13yNmf9VLzZeI="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_5.0.1_1536588476492_0.9057691847673079"},"_hasShrinkwrap":false},"5.1.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"5.1.0","main":"lib/index.js","license":"MIT","engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare"},"devDependencies":{"@operational/scripts":"^1.1.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^3.8.4","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.10","react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"419fb6743497c571a4f6a71c30045cb5c7387dc3","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@5.1.0","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-y9rWQHl7dJyEHKDCRQJs70VfCPxnnLGJhrAMIGxSUiPq83YwwrKwLY6uDKQ477e4a7rsJ06+PjpakJHyfrR+YQ==","shasum":"6d2cc215d8506dc5f55357e4911b50329d7eb1a6","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-5.1.0.tgz","fileCount":22,"unpackedSize":96361,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbmPf9CRA9TVsSAnZWagAA9o4P+QCev/gjn4mti15lpPKr\nA/3lwVAWJz7x9eimrj4mfo8Gsxv0knKxb+zBs3cXNth2cXK/k1ueQOX+yIzm\n7e7qktzgtYCX/YBeHmloJ0TXk2DyAvhAHhneJ5ZszKAD9dSGowbtm1vWJa/l\nxZPQxtKxFssgeATVItwkgOOeCi+FyUNAQyekDBU0cqXFeoJraJsydLs0u6PW\nYUTOk2slMpdE0F7xJ3UidTHpQp9cyFEJRChr4nIdiCAWgarzHEBYeBUhoDCq\nX1eO9++wr768pikz5qJYKE5VwelzQe9E9iCtY5YfjO3FA1A2ujP8E/yfPTjE\nZ4tMQrA79R1VJ9s+lgbWwY/oolLuYXZ87HlhQcr8HduT59WhnkwHWpyTu/fi\noUf/Gz7jfWIB6Y0HQzde3MQmGZkOpBIlt+C0FsLTBxDWVfYjR77y3wGGFWzA\nQ8i0fmTTTqBMVj0txLU7/0KQlOLNkc6SMQhK5Qp/QRZnKjgeXhJVqm0EjGz4\n0Ya+PhG+Vs8Vg4WtDMppMngFyyX2LAoxtsoJ3TZzzsb6KG2YCYBGCIAJC5ws\nfFwhawUP5lqgmJYvPbP9vYi8znmzwHhUPBYWwfjhsLi2Y564DWePfT9dHVA+\n2Z87O+UucHI1XyMKSMDDw1LTT2sdz7PFOkKQAsLtlVK8+RPiMsJekzRH1s2E\n35DG\r\n=4Uah\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDWDvIVLThXHJibBIIg26YgEv7v24aq/oLBwNFqUYu8kQIhAKWrakzoh18JEv/mneVQGIDptZj9Icv0tzLowxLwQgs3"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_5.1.0_1536751612661_0.9072400386297632"},"_hasShrinkwrap":false},"5.1.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"5.1.1","main":"lib/index.js","license":"MIT","engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare"},"devDependencies":{"@operational/scripts":"^1.1.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^3.8.4","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.10","react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"e5e7a5f7b21b59c3fb05f2608dc6c4c62689b6d6","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@5.1.1","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-UPT+fOUKb/1MMJImRIQKa4NEJjXNmdPNJ45hzeuhtZVJRpog0sf3aSY3t/GhH1mNgz2AIBxfT0TYbXAO4WV9Gg==","shasum":"536549418906c8d9d747e8da7b9f20b694bab362","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-5.1.1.tgz","fileCount":22,"unpackedSize":96634,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbmbk0CRA9TVsSAnZWagAAH8gP/R14m/FvKRf60jQM75CV\nJpDeDHUWsfNobQGzkcm+HVFdEJwRwn4YoBJ0Zgm3kQbvn/gVeZAyCwXz0b26\nsRi3lH3NkKNNTNnSGYQ8O35nWuWu5CW0bEyF72LzEOYOaWLdOnELewidOzlg\nfPXCmxHGWKzsizf9HPX+QPVnsM5MOY+vN/024wPDq56WyL0Q4pD++ugT4ZvR\n4dnLxaelhlL1x9fGlPaav36J0J9+6hT7E0fcpprZxIKH2CAF6930pAB4upkx\noDxwQeVjqbkIeh4a8f8TS6EhC6TSV0o4gwkD4jwgb9yIrD6M5uUV7LHqkF+R\nXpc1hUUF9Gz/5VcAvvmG7qNIjLwdMl/q4qBvnDH2Dgst9eeIwu0roipey+dZ\nPnLw0bOatG3DxZlN+zU8lMdlbExxQX4RVyUcceqPQDo6WgwyEkEg81SXB2AN\n6ocuXOe3Uz5D2XPMeZuDqCFfSVKyR3AfBWj9CaIEJ8CTyZICGg6wsugp699J\njnmPwQU3afSsNH306f+MW4T5I3L1lr9xQPrA7cATl8kWDPbXnr02w8yICDIa\ndpmYR4/zvBE45wYlrFMFV18Wj+BOTHuva1T1xUcc6RpAEkOFVA5UUqrx8xyS\nXoOoL8LytM5EzG3i3T08C8ZzDo9SDSOQFknWum712ZXt3+e4HJ3rgufPVBlC\nvBsH\r\n=DKiG\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIGHrCTWqz2S+kOjup8ygg0I+0ub69n0LDxJSbBMISjvsAiEAn1zBGrvHaVPEu4dB+klGH1CYjMOnRPfFoiiLJMvGY2A="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_5.1.1_1536801075822_0.24351374789765767"},"_hasShrinkwrap":false},"5.2.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"5.2.0","main":"lib/index.js","license":"MIT","engines":{"vscode":"^1.22.0"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare"},"devDependencies":{"@operational/scripts":"^1.1.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^3.8.4","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^9.4.4","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.10","react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"55931d311c81a8389a8c48dd73e885c17f3cd809","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@5.2.0","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-4a6Gk55A36iy6ojiFtjY43pi0RIkSeIjmjU5tauzSIggM0EGYQrDEQQTjkRBdkj/26BbeRgB13PYr9JpjYFF/w==","shasum":"3ac5c8814fe6dd5feaa9c1b93ba5a436b3d3f2e8","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-5.2.0.tgz","fileCount":22,"unpackedSize":100775,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbmuLxCRA9TVsSAnZWagAA8JMP/0OuHJeIf9fyJM53fuTX\nhv1dR+cLypYyBg1nCZccqzKs46n0GTca0npopZSfMCHV+ue5sDtsvPwt8qkZ\nTlNtzwscFhzeZETtxuHqgx8GaO3/9On6NJ3un6TK/Ot1bscIcN3iP+tPOXFA\nBkece3Z7mxvuhym0eI7VbNJyzyrqvdkq56lAcvOMsl14St7cgcv4CvI30DSe\nFz4k0ZIrsoR93pUqdbgf5PtXmUi9Yb4DwhqHVKQH8818f55krRe82p71e8+4\nMGT+6GCtGs8RU7kFHsZZqWuemRVXW/rHH3AVYzoTtaMyjVza5PyyfY2PfgDs\nEiK7/hsNghr0q3UBD9jRBssTkMBhbAMUn4BMxpzB3BTYKHIIWqRcVjleaFCS\niUHufaY0kRg0w5y9r0doz7S+3iYeGFpelDnuL1OTEydwZNpnacTuLe/oW0er\nVK3ffrJfYsfj31bCBTsTL9AMBQDv4KAxcj/WGUbRxmmtKQLo4gFha2zVx6hO\nprKRHAW6sgvV1GaGX7WhBhJySYzU4OcELcKYf2+Iq6UBOv7H7fYHiwflwCqr\nmCros9ZaMx3R8TFlWGjw0RlQPmBCJlDbYnnoz59GvC71Cy2C8XnOiTIo+5c3\ne90GUntTsBmVd802M1IGanHKCKuzunIH4uoM/zjBYEmQsK5c95zzaw00vRXC\nWzr/\r\n=iMg/\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCQMfTdVDfDcNsNFLMUhJO2Jic1z/6LltAelBGfB4VP4wIgdNsmuw8jPtjQFYlKwh1FfZdIYqF0G6P5BxFdvAW3oS0="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_5.2.0_1536877296219_0.5738328243473076"},"_hasShrinkwrap":false},"5.2.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"5.2.1","main":"lib/index.js","license":"MIT","keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare"},"devDependencies":{"@operational/scripts":"^1.1.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.10","react":"^16.4.1","react-fast-compare":"^2.0.1"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"8ba212d3a94e506ac7172bf20fd0776918780937","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@5.2.1","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-UZBVjkH5RMpODvSaS119GTwLGCYTm2rbe3G8zAPt4p8OmtlCL52xMWZkvjnvkss9YkP1OBghvQdTXxg6fekoAA==","shasum":"c6e99c27d6c08f86a1ccf9fc87804cf355b1eab8","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-5.2.1.tgz","fileCount":22,"unpackedSize":101191,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbqawHCRA9TVsSAnZWagAAQCkQAKJZSsyuZ5G8VUaQhD6r\nT9sj5Ivo8zaMDf7/QaQFbaZ2DV5eU5qB5gxmyZGZJFZxcwn8RXy//BIh2494\nLhJikR5FzuHjklMzj6cxa3XCNvnOJQru7fmTjRrV+VrL8EuAnbcQCSwdMZeQ\nbDez/dhg7UMWGkdOJHByKsZDQI/0YDWjfLQxqQ4xfjZlcDcoFNGY8K+tgz6n\nVApeXmER5IuPMSUgXYjiEmd4ftrMMPCdD1oYSQ/rL70Mv/lau5r1jVAJ6gN/\nDPXlNa0bcTnO9BDuLNuCmml+mH45iuDJn++teiVixII+IsZO9EvASy71U/Zu\nwM1hPyzXkW6vH3SpYquEYHMcjh0IftusUEse3rx7z9S7Yvq2bx8D7KTFa7g9\n2EqPGDgxJHUzuJfm4+wL32TUjAnVF0pvPs1C3D1V4X3zWmkgB3VlIbCzFLE+\n9eaYHJeNjFW+SoLw6diKPfSztLE2EqCrXbqY9ZJaPd6v0oO9FYR2Ho61ad8l\n8g8NKcKgKJXlmel00+0SAiwy/FdRhplY91RmvXgs9xhwqhYsTXnG9sdCP0kH\nEOawKBLhhYKBfgL5Rh/P8uzMgJeVTtkYVZOAuFuqovzvV3gsrZkE4js4micv\n+kuN9TgPPf/0Tk6G6Zu6fRtZWannmJih6LjnJzKpuYsec8wCdoFsC1Pzpbas\n3pm8\r\n=Dv//\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCmF4EIelRkIYK8jJldrSeiruAVglPjYx5ymh76gNMGewIgANoKTKtodCgLKgwHlncqvzpiGnJk+lRXKi0fMFlAfa4="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_5.2.1_1537846277891_0.09875198325020751"},"_hasShrinkwrap":false},"6.0.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.0.0","main":"lib/index.js","license":"MIT","keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.1.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.11","react":"^16.4.1","react-fast-compare":"^2.0.1","url":"^0.11.0"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"da9e7da67d4095f98d6d257f909c1b81ab75690f","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.0.0","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-7Ypd76XRvE/JEd53nsJY/UP1Ip3Q6Zt4G9EGZVAaJFoXLEGG/M490FZV0hUCRA5+7d3fmCcmP0rj/c2OZs2Khg==","shasum":"ad37e5cd82352f9194999d3e58d43018be4f6277","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.0.0.tgz","fileCount":31,"unpackedSize":115795,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb2bzQCRA9TVsSAnZWagAArtkP/jgcRuQ7+Aq+f1IY4J5T\nlcoO3z55GK3FnmXYtOALXY/iX40AW8MIxX/uX+TR7fnrEBHO5g62HjOxflgO\np5vTjHfxG17I9qR2zQcphZi7cMAvFcPVmygj2ASXaOOu1VJVkmux7lROvIxY\ntUb0AMxi3DMvFu7G9XMdMmBbxPor45mCvzrFS0gaoviWZZ8BfGMTWwafcFEd\nJ1KyPzDr/1GzwSLYZ/Pp1DxTJYJGdT5g8TKody/sZAtMR/PsL8Wf0dhR81+r\nIoiT1hcErTn6w26qFkL3fS+AJ6V/59q4rT2L3/OT4FHmJdk4Ciy6pu80kQnx\nQhAM7iaURGy+nLVhKwBceG4QpU79SsarsSARWsTa5e7t2BPaKrUHTa15ZfPz\nzdHQgEmP4+CIZvf32zzeeh9rm6Acl4xx1ZQcDZZgwfHsuyTh+u4GnWyQGEL4\nrHIpx/KVTfmBW9izm/hMNFzKvnuCSYYD76FX4gtCsBS858tgl1FEewy6Fugo\n92PH72yBfQThsT8EtoaWNDs1zCTV4bvDFclPxVRKNAjwC6b5q5i3fcqd8IF8\ncYhwh208/rFSjQOIDkvpoyB09O7FFArLgy7+XOzKapWcEiyDg6k7di9L8odx\nbVfAXE3O7MwogHVXMtuaZ0qogFBSqxBXYu2TorGGd4POAQXem4GV/m5lXIo5\nbsdK\r\n=vd5Q\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDkWeKm/9Lzrvr7lvro9aolb5C0IPWRDKSrkmahlzss6QIhAPRkIKLzCZ5SQBRQ0/WkSrNEi2l1e8aVmclCHDQ7ossK"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.0.0_1540996303625_0.5846220752733913"},"_hasShrinkwrap":false},"6.0.1-1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.0.1-1","main":"lib/index.js","license":"MIT","keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.1.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.11","react":"^16.4.1","react-fast-compare":"^2.0.1","url":"^0.11.0"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"660788b1a10b3dcdb0933485e4f8bd770a36c36a","readme":"# RESTful React\n [![Greenkeeper badge](https://badges.greenkeeper.io/contiamo/restful-react.svg)](https://greenkeeper.io/)\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.0.1-1","_npmVersion":"6.4.1","_nodeVersion":"11.0.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-C+akg1Sc28mdB1CsU+mrs0BlqyyIsRxebwl4l5NXTto8viuraJDXsnjUwbE0PylEICVJe5QpyjIvAGVz/2c6VQ==","shasum":"3c5616fca59e4a98037a23e9faba5bc9ffde4722","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.0.1-1.tgz","fileCount":31,"unpackedSize":119127,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb2eU/CRA9TVsSAnZWagAAVnEP/1tVnca4Yaejlk1AAK2A\ne6PyQMp0+AwjM9ke5XEA0hCQYJCT6j7qJ22JchhVFUDB7eTbdFlkV1UvNf4/\nUO73gdLwlb34/BjoGz7pLgQO0QDrSqQvdLqmA1XuXN7pkJeLmaARglNdMPHF\nnUB8tKfpElUYkIn5WItwS2PVqiQiEuu9adELUEHGFmSV3JtmqQfiOg4XwnaN\n+weiZ8APBK3rCqJ1WQas4aY10rxQBSawy1gyGJArh5YGxG/yefwqPH25OT3n\n8Hju/3OX/YWL/01DAG8V6QQHT8R2OUf9rF/HyWhNBd4Abby3IrDD70QS570M\nmIfVKurNjNE6bGQtKLCWJ27/bJ6jmc2/Bsxi39zOn8smqtO0ai6SckSkG0Ke\n532AobiBwWUAqh2fyIsoqh7CHRVChN9ooHGbAAxuMOIPk+Vfk1sG56Dmzn+2\nkoZEwix+7h2yKwMTxcBiqMdDFSsrCUErNuurLr+ZUsCFxz2vMxep5R4qC8+/\nzP7tMajw7w5yRol16XUBXt33jhLZXNP2E3o0kskpoZIRo1FmZx9ShdW8z+8B\na41vEk67Otare7baQ1G6wmQjbRPjv5hNuv1AZtiFJ9N207H/ZqcvDWa5W/ZT\n1PnHPC3ScGTc/C2WxxWtz64z4+K6b+/aims4+mW/NcbE1H9uzLk8R1766oQt\n3BnF\r\n=WlcC\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIGKwrZ2tRSv4qYBnTjewhs0+MdkiXNj11L7sKaPzNHH6AiB0k2BTXWoAPiw1T0U1P7hyCyJKAoGYT47A9pUtFfDJ9Q=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.0.1-1_1541006654572_0.18936259168536784"},"_hasShrinkwrap":false},"6.0.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.0.1","main":"lib/index.js","license":"MIT","keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.1.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.11","react":"^16.4.1","react-fast-compare":"^2.0.1","url":"^0.11.0"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"428f4d272d41df739443d5b2626b8a7d91c03935","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.0.1","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-+faQoAiQI9vl0mkmDR1emJ4Tuin1shuRgAsQO1ZBtoHeooFieapjAJQ2QhaCuoAHrF+FIuaeSimflXwSKzG7xg==","shasum":"05dc3c473ce1175adf2c6cb52a1ddd2c27860905","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.0.1.tgz","fileCount":31,"unpackedSize":121234,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb2vnoCRA9TVsSAnZWagAAJgUP/RJBoi9wuLJOgaLz25nZ\n9BhhtuWj3k/KeIcpvXHpWspas2TbQ7VQMs/OfS7OlORc8Ra52LcfhRuUzjb1\na76U2BnXhq8U7eWHKLPK94ZjR5mSI1hHJ45ruZkLtEgY7seaNN4I4N+Q+3h+\ntx2DOnu3wKVxxVyYPNHPEyTmlHsrMym1KKcIbq7zpLhgO3MC9sCbI97WYnoX\nZWuDrZk0v85pCmYENNg/Rfhv/cPTo06pHhUagIhNf7FPwtZ1VVeuEsQwKsJs\nAo6Y+dL+8A1U5dJhLIOQMBpcOUC7OUOizZOflygBRaF5HKfPXmt6ejNPVhSP\n2OpOFG5sm4c3GfbKUGb2PwPyCJRBHnMYMoZcfdzNGglUXULP+u3wcfB34t8B\nWPl/76W4mP33cb82aILS+opbHpGAoobv+gqDPNR2zevvSUPQPH0hLTdx8QoD\nuzpnSu/EYza7UmfTPKNMas7B+ZP2K1T7fGAIq3yFBvTrX8YTz90k5OwqjEYd\nyWO9zvA1/q8tVEhj1KqwrbptYBgitUO5sLogGmTSC5oZrlusV+1d9las1dNc\nOIfjgnF3ciizNkbq0urENYpfgl8OuqDMzN/d1bos1q4LJc92Mz3W0CkYndz2\ngCCwv6HkyeUGtTiOkQlFyApc0van+sLqxaoVgS/H0ixQ0yris9H05caqTTOV\nn4o9\r\n=XpMx\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIBz0NOeowS+nk86B28d6ejEKyh5B/dXZ3GV8i8XHn7PkAiEAt6cQQHr70AawCgt6cBWndyWDIG/sQquv/5KyUVj2IHo="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.0.1_1541077479897_0.34106790518931884"},"_hasShrinkwrap":false},"6.0.2":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.0.2","main":"lib/index.js","license":"MIT","keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.1.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.11","react":"^16.4.1","react-fast-compare":"^2.0.1","url":"^0.11.0"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"2d1891ce4d27a847eb43490ec1997d22ed9288b3","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.0.2","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-kxuWwMVHQeqhA22UCMVjUOMgwE6Tqi5MuKI9NfEH5+dfB2MJOUKxmk9lK++lDIz/fJFjfRxOPhO480M6kWQxMQ==","shasum":"9b1465ab0fbd3e6a2a6b6b6effde7e5f43f379a8","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.0.2.tgz","fileCount":31,"unpackedSize":121706,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb4u0mCRA9TVsSAnZWagAA9M8P/0ZHcAxLJEZ/YQl4UvJL\n0IR9ssl7igtP6nyW0ZXNQWRUiGN5B0QMheIIGWzljVBa8opYCidItjgKTk0o\npSP+/zJv+IacLLw42JE0h5//3RQf0ch9IeUdBaw9xjqscbBlVHSidQ243sYJ\n+Ujhpvlbf+yryx+Uh4g+nklrubP5Ve1YFr7dBgVlo7E696sbA+wdFB6cxoef\nGcJubKnwh+imvuOKyb+hVpylynGQ6xIuO2aH+ggptwq7AZ4J6QKZz8Qq8u9H\nyVs1nI89sCLt4M1LIJk3BxKKH9skeCCsokGzf4QPF4W661/gsmmKU+SqIQnH\nuRE4l8bqK60KBGq+RAl1xfeYwgO/2XwTPZzq4suTCU67kke9ePKyHuzkMRom\nFv+ARcH0P0xhBT0g73JDSP7U3GcqLqIXtVrbx8w3HSisFetB3hQUZH6IUcpn\nII12vjzKSZ3plcMELIBAEPlzbAp5fC3smmGsvsGg4CiUK/FNc7zdnY/wdK5j\n7dwNoouLpN5UxydxCc+Tybi2cAnJj7ANikqfqrH5swykJF018X0eR99NBzV7\n2KhhTGVFMfuCwnqKnEGJH4ZFsaUXeRkPferMfIjqYijhDrlY0Htf+nrlPPYZ\nfq/c9URTtr7hS7EBH0h9ttXLGA9s9wcWQVP3Kf5AgWP1/++o6TQvim1QT68M\n0fGa\r\n=fVQT\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDHuRUmf1q8QADgqdQOgj/4AMBUwmQVIGbaWh4WBn4BygIgQ3bDDls73xZThjEAxgVv6nOu2AnF8XNeI4pTbh11MWk="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.0.2_1541598501716_0.435129615372726"},"_hasShrinkwrap":false},"6.1.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.1.0","main":"lib/index.js","license":"MIT","keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.1.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.11","react":"^16.4.1","react-fast-compare":"^2.0.1","url":"^0.11.0"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"61f6eb00dc273c720881a25cf2895bf9a4408612","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.1.0","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-ME+Qu0DfBsHV0dl2XmA3H7FBDAGWXZNuE1me4f6GeEpI43ZVqysYkV9gsIuH2WZO9GiYHl3CMejv+jX9lK4L/g==","shasum":"aca828758963caf139a2bfef13dba92bed4fcebf","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.1.0.tgz","fileCount":31,"unpackedSize":122180,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb6tRMCRA9TVsSAnZWagAABtQP/RvNas95O/eqCsTCG4hN\nLYCrJMjnvf2fs1ui+BSQ20On8l+vbBHiz6h0X/1qxHBl8NOUU0Afh8C+arGu\n0iKx98AWKa6+UriqPKv1UZRjMpLQTSsxr1pyfMM7LwaeBWxN4DOPxbp7LtAZ\nNw7w0y42kod5lnwYHROfEcx3q0PaCpbbBUCeVLylhQ4HbkClAumlw2g4j/gC\n3Db5RPVX5ux64xzWUabp1ck2imOiK4aHedvgDJ/gLnJLTK2BqetG7nxs0KOT\ndPJBOSCdUS1SE++coD8LQU2RV0XZyjQxX7L6EbdIPxJLMYAL0vmSVXC6wLuy\nmRwFj4T86ewMeXEJREEp1SK+wNNNPokO8/AwXxB4ovOQUudGgQcsNuCPjN1t\nzd6YbcWXcJmv71WSA0SbtTh63Q3zbxwVNaZrpmu+Jz1iIOTlU5LPkiQ5jKod\nqdNZM4BB6bBMZ6+RLUtbZvK5BUMySAiKZMVTA/864mvxBaVgtjH5L93sQUJP\nFR/OpcQqev2brAh3h/n1EZzl2I6i8dhKO/9y9l1uVI6RSo9MAozJdlvownj1\n10HejvtyPaG88vxGZ7OsXd6At0ISSFQgmFeATrUh8YCMoRNlyRVLDk+MRTl/\nRkxWGVD1VgF9sNO9oChpt5x6LE6SgLmzumdSrg8DJBYzPiSuRlsms6B5ydWS\nXYm+\r\n=LZfS\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCQvBVWZTjxi5Gxl3P78Ndm1ryyODD/JUwEbfD4ilugqgIhAKo4s5asVmgB9pcxOn4/VKVPqiNxaYwTj/NzE/ySHdod"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.1.0_1542116427344_0.909872934937594"},"_hasShrinkwrap":false},"6.2.0-openapi-0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/react":"^16.4.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","openapi3-ts":"^0.12.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","lodash":"^4.17.10","openapi3-ts":"^0.12.0","react":"^16.4.1","react-fast-compare":"^2.0.1","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Greenkeeper badge](https://badges.greenkeeper.io/contiamo/restful-react.svg)](https://greenkeeper.io/)\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react import my-open-api-spec-3-x.yaml -o my-awesome-generated-types.d.tsx` :tada:\n\nNow you need to add `qs` as dependency to your project, and you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"5a3d3ca13dd96cb8e3ee0d7ccc5619b157d733e7","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-0","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-li9PkB78sPqSSbteI3OYn1FISHWQAiagWtupt1gpocMDYacRorxWTIzdQlm9klSI9Bv7WVGarEsdkP2cYj/z3g==","shasum":"37c91557b585e76e5977a899eac2dd16814d8e37","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-0.tgz","fileCount":40,"unpackedSize":153202,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb8ta+CRA9TVsSAnZWagAAk0EP/2brOrnP4Xb+LUv2rHS3\nWmvrqCTB4z5+sHu2W8eiBu0T5Ww6VALyYcqXv8AuYm2XIW8GoMpUwoW8CGIv\n8/bZVZsedUbyvnS5mWxgBJBJbc4Afa+00fdFYD6vOgLQrE1pLq2W5M4k+YDm\nUpDGlQySgKKwpKp6SM5G4QuLR7iFlrlYiOOLSjP+VAdsQDhHcGkRSAanWZTQ\nBYg6dlC0cAJFhZv7jiO74yq3WWoU6/Iu04FdZDdOcGmB55Fdk1k2vkQ6zzwF\nfRt+KIcr4ukNrQDLtV6Jn82bC3m7zocNex4k/dR6DQkWJTXsemNFKxFhuw0n\n0jR9cfs+gVFgbRrOCZD9y/w6TH+vBZ5yDtyItrIDuhNDnlVvetgubru0aw2y\nMEpZj/c2cINjGQKmLQCkKJmg8uC9fz4zU2gkqN8YlHmdIOtvR5oborBXSEOj\n5dQ3QxWQiOjwbPQYcdkfHNk1obRq+O3OgEJwOybNp/EnaH6wzzqD1L9c7OJC\nONqAiZAEGEUICoyLzK1SMwvUExm+xfsh76qIJ/x59daoNxRyFA43CzrBH0w6\nEUhzg+XgDaGNVyPNdVJ4cXFmLl7t5srHlqz3+2A4YJrF1bQLRLycMSkijtPg\n+A4jqHXney/XbhU4lkugzF0eSgjBCB3VEiD7kqQBEdIgr23eoyS+L6RhIfs5\nfxDR\r\n=uOjo\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDcu8GfNlnpasaPipVi0Npcy/yMd9jZRm/sOWTOEt3dJgIgI/tvx2K6IkGpPISBxLUeEQ0JgnF7zEjaJAiE3O82uTU="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-0_1542641341883_0.05634189818241753"},"_hasShrinkwrap":false},"6.1.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.1.1","main":"lib/index.js","license":"MIT","keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.1.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/react":"^16.4.1","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"lodash":"^4.17.11","react":"^16.4.1","react-fast-compare":"^2.0.1","url":"^0.11.0"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"8a6ffd7eab28123d288e04b388fe2dc9d39263c8","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.1.1","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-JtoWD4SQFb/O22GsoiH/oVpO/+Orme1WoCaVcG8vL/KblNXCYVxxRoD1yIe8ilwveKfNBNY4ZqQf0xh4gFzyAQ==","shasum":"9c5aa090473839a3cb3bd2accf434d8e670e41d4","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.1.1.tgz","fileCount":31,"unpackedSize":122418,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb89c+CRA9TVsSAnZWagAAXxoP/1Q5dBV78HHupOj9r4d9\noR24iYsuVg/nA/tTSX50Ee8E4czBZKxndKLeNEaY6xtx8Q4yCcEI+y9smKEU\nPFhAGJcgYa5vmewUFeCsKgjHJdrWCFRIyqWXMT3k5eJPelTPYtADpYslpHQo\nlTlT2b2AWuairM0JISUiHKNo+a5WRGBcJ11J8xmvjCPgVtUAND6zprwM32bO\neKb4HKFNyeE+6PE037p4ussf8MCgUBs4EhPUw3ADxZn+MOrLtW6nX8fmlZ8F\nuby02H36jX85H8WOHDM8oiCMuJ9ZaDMYCnbxPyD7KYZ3npz95LsU1KiExfoz\ne7IJloQvospNDOXLpU30l50Uxdz2oV57ARH9lNIZnrIZldO/jqNShWjaggdW\nJiUkeBw/sJ5nnFT77XL0EwooNledhUpGvUoo8GH0lDWV4rCM7XjTLWXizKdj\nA0EDFZT5pcrPaaVabl8EYdor0qi1WVyP5PyJV4G070tj/ulKtXVcrXkBa/zY\nL2zfAvml6TibboqKPVNcY20I9Gs4Ug67D41eDpJGVQ3UsPDarxXt5zLXuFPY\nc+csNJLZpIYbSAei97BTV0oeGj4WVTneRZ2JTVWfXCI4E1nu+GlYaxYijCaK\nm6yf3v6xzrx16qXkQlre0hes+nJLNR3Ce2Hdt2CttWzCLD+xu3R+AMhqdnvo\n3V8f\r\n=7dj1\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQC7wrPgpcTwsVt730j+2zOaWdsKv2t/sSxxl9Y2OIMGSwIgb/uZolhdKYBLdIlLinTESsKvKmQMqmYo4fw6Jx9Wnz4="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.1.1_1542707005201_0.9689802746597105"},"_hasShrinkwrap":false},"6.2.0-openapi-1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-1","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/react":"^16.4.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","openapi3-ts":"^0.12.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","lodash":"^4.17.10","openapi3-ts":"^0.12.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Greenkeeper badge](https://badges.greenkeeper.io/contiamo/restful-react.svg)](https://greenkeeper.io/)\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react import my-open-api-spec-3-x.yaml -o my-awesome-generated-types.d.tsx` :tada:\n\nNow you need to add `qs` as dependency to your project, and you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"a04e0e9a4c85c0384a76c51c390320e11b7b346f","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-1","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-rua2OXonyTiBSS4DKdS027pBHaPc6OTCMiaHTt+nEUdjrX+0mvHGBLNkMhxZDrCjmJQtNqGTuzVuR7d+H+dyoQ==","shasum":"436ab3b8e93f9a59038561d80eafea33532dd960","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-1.tgz","fileCount":40,"unpackedSize":161618,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb+ARPCRA9TVsSAnZWagAA+4YP/1U4f/vJlb+1jLMoa0/8\ny0o4pXzDbOSiLpi/1LuN0Wn84rz86/Xh99qe+7r4FLKNVLrZq5PFc2YmwiQR\nkKDeImI8COM8LaR9hznE9BcdlaLUU6UxOUgWmiU9YcxPWMXxgxj1qkNM9xPS\nbcgQf/UsBvglGXa9+jSGd4UPtAFn3brUJxc0Uj1wNfCzgEJ/Oyp2O+LqA7pi\n6E/FkSo/upcmULaE1NLJWeDIv2Aq7HuECJio1j3HwfMjDXjl8h4dh1gny48s\nNNVd3fe6Q6UnbEdqTwtHp1awnujNucNXhHEUx5BRMbvZEhv5LahbWXIAcLbG\nA3oQIvYmbg4T7PFMWiV8V5y2fbJGnfztOn1xzy5zwqM3zbA3Mf2vcxj/6qYY\nyyZmL/V7uWIKtlkiJsauTujICd5XrbLlXcVBHcp37ynewDHP3nulCllLMuMO\nQhBoh7UNhoQXfPYK/tRyGv06jSgOe4l6tTYp3LnfeWx9hhgCfJaAOo8DfuAo\nMtb+s4hSOmrmpi13Hs/BjzeB10SxQhz2ewhigPhUsOaeOYQNBQo1+cu/Ax8d\nFILEgg+74UbL1eP6jRaQkMd+L2kRXzlmnF1gUKvl35a6IZJwlA/bIvl+lojP\n1S61L4/WGsDIbC3JSUyZrpRxsbVucR/WEKZ2tZVrs3U7buPnY/BwD0bpyxaC\ncoEj\r\n=QqAv\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDVIQbcXwH8KV6rabpD0RMBsEq6sU4I7sM9NxV8T5ctDgIgUwHN3brh/g1wqfEvuuD/mJl1e5Pfo7HUWVHQHvHWwxg="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-1_1542980687078_0.46460924351956967"},"_hasShrinkwrap":false},"6.2.0-openapi-2":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-2","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","inquirer":"^6.2.0","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","openapi3-ts":"^0.12.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","lodash":"^4.17.10","openapi3-ts":"^0.12.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Greenkeeper badge](https://badges.greenkeeper.io/contiamo/restful-react.svg)](https://greenkeeper.io/)\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you need to add `qs` as dependency to your project, and you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"8beee73108ee3024569dae2c3c1a31837196a2a2","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-2","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-9Qc88YxABxHOKj7WlDkgPEnOvz57uHk3iAANBroGQA31lTiCLXF5KXpEi3Ru2t1dfdfsB7rDfifxGycaLIEASQ==","shasum":"ae970f244522ae47becac23092fb98839696c9ac","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-2.tgz","fileCount":40,"unpackedSize":171935,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb+DrSCRA9TVsSAnZWagAAwooP+wagXIN5EyTasWeY5Uef\nDSuVKLtnn6hfbm+uDWQ7C7QECEleOFMIUO7GYynMKzg2CJqRojb3VS8QlO4Y\nzaAr93HnJUHfFriODOsvtyieenTmsT/RD0z5Y0lu0dY0kdF2OZJCykWW5DFo\n0JghhTMjULciDj8wDbbDtqHfYPf+br75wlOsrYesZYZohYjYsCIIkFfwc3g7\nAmA6I/lRhMSPiChRw1jc1+TWcagtOydEhBPwEOs1RuswXKjNFUo5JhRq2E57\nxoc9/LI03d2Z4egafPE/Wcl7mKHMQThQ72ITXO128xGDkr+y2lki/tVMvPhl\nLmKV0xsAt7geyeHbSmxBSg9LrPlF5YZm1+tUDQzODtEbCeSCWarIfSIKbsxB\nqcuJ5luv5gocTOh+T6Bgoku+qrei6aEscc3JaREF6TrCkb9YMW8WTmv77uAT\nUM08dMGdR2mbHjdqm/sqxMpBB/k2mdLQzFrgGsAIDAM/RHTGhBGGE5dlesKh\nH/gFWbHAjNVHeRBC2PqSW/S0k1gdYMuPXQxHCyjq8foTPzvDx07tuTa7vlk9\n2rRDl0qHt4AB0iMnsoc2/3HDV75CB4oB7HnoUGaRy1BXWlGDh8OUdNC4XddU\nq11toXxGFYKoeROz3o58O5vVELCmPZhWVmEk6WVHnmAyvGTbUAOSs6+r/dX2\nWrnb\r\n=8ucC\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIEnu9hiNhIaY9cc8tyLANe3jbhMleuQCjae9Kjy3wy9FAiAEJyHEck00nf9yQS4/k0vxK/9bvscEZ+TLzTFIGZy7SQ=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-2_1542994641869_0.07606404288150181"},"_hasShrinkwrap":false},"6.2.0-openapi-3":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-3","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","inquirer":"^6.2.0","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","openapi3-ts":"^0.12.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","lodash":"^4.17.10","openapi3-ts":"^0.12.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Greenkeeper badge](https://badges.greenkeeper.io/contiamo/restful-react.svg)](https://greenkeeper.io/)\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you need to add `qs` as dependency to your project, and you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"8beee73108ee3024569dae2c3c1a31837196a2a2","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-3","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-u1SAqOHNI/e4bsLndbYOroYpGIjThqlcZ+IfDWI195X+f9MfBOzfMlYb2/BSNuGoz9Upc5EmHuSNgkKWwz9zOw==","shasum":"17527eaa9448a9789a07048f23a17e2f1ad97577","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-3.tgz","fileCount":40,"unpackedSize":183994,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb+D2YCRA9TVsSAnZWagAAm2QQAJbj4iy95RTBJ0jip7XH\n8ZDVgSF9O908rry/1eVZ2VQdzcNjzoK0X32oKZ797RGSF8RdtCFZY9Utx6jS\n5bIVYKgWjE+LhOG9Jko+f5j5NrwOGTkRc7pMU+qL8whf1WAwSyRBELgsC1RM\nVLrwkf1dys0TpbeZ5v1AAVphbHYST7tJ5nPY2MkJ/l9oxHFv1yFzlQ9tXfUB\nk6ZL764M2TPQNBshJk5A2Ns2HStxcZTO+bkeTDhwN4ykMjZdjr7Npum4Kd86\nVWaAsifYpjbjNQFI6eIzUviHBGcuuQXPzxlVYgiirMApvghquOt6vjbU1fGd\n0wXW+PJFPzt+rew3WsK7+oWD74NPbGDuXDYuklF1YItIQf41+t3/7iE2ZTkl\nrtvAZhatqAo4hboW6Q9oQIm2YGvrYaDfNXKE2hocwLQ/bsBezDa9Ir2+3dz1\n+/Mj/W3bXBB+egMmn+YhCYC8zUwOS7L1XCpc9jH784IwhWrEJevd0le1iUMU\n0LQmFZUJ89D5wL10RUSbE8bkOd56Sf93zQkCbIzFjjuuEyFXTliw1QyQrdaj\nYgxrWC31z+/T/6zKZxYc8qWljEn04CsWQRpw0mzfldorRsGOFf44hPtOBfMV\nrPluB3PkfiOGETBDgGUrNTsL2Vlszg3waKKKH6XSkym9egS7Cd7f75fYOTwG\nF8rd\r\n=oPiz\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDoEziRGXso/0XKTLrgJAJnbdHMvACEOntREdLLo77YxQIhAJvvwKi1swdXnKGSh5I8pNbFJWszda34X1d6oeplNAif"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-3_1542995351980_0.13731625577980777"},"_hasShrinkwrap":false},"6.2.0-openapi-4":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-4","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","openapi3-ts":"^0.12.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Greenkeeper badge](https://badges.greenkeeper.io/contiamo/restful-react.svg)](https://greenkeeper.io/)\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you need to add `qs` as dependency to your project, and you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"8beee73108ee3024569dae2c3c1a31837196a2a2","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-4","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-hc1pUooS0qAOCUxROholfwB+M0AhJRhXEannlAA2ohNar1951cbHF7CmUP64X5jAFsswLQ4gexIfOoW3nwYYCQ==","shasum":"f12a1bb6845edd6142f23e2eaa5a1f5f05acf4df","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-4.tgz","fileCount":40,"unpackedSize":183994,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb+D5yCRA9TVsSAnZWagAAzb8P/iTGRnGROsjisDmJB1gI\ndgm9vUHvq9zIGLxjilAIaNWrsPG46+B5es8Vkv3tvz1zGGBUWxb4IWeUf5vz\n8ozYWbFvyNMUZb0wgYz+o/ifR+NN0lqjDm+4S2JSSeKnLkOvVhZ008ukrP3J\na81GBCAh1h9p9Yb+rsGB+A0A6V+9fGEE1egoiNP5h4g7o5u7GMzcIljL+I6i\nUD4FKaZG3MaZBXKrXZ/p6GUzqOj4rqZL25xInJ3tFwcz+stsUOowIeq3IHU3\nAM8j0JZYsjE6kO4b+Srgw8TD6VdFvohMchnv8V0fDuPyHCZ81MZ9FekAy7jJ\n3of7gB5Koa9HsEVnKDY1E5JPI0qlCpFax59k6TbA4rFWwyao/CzfuR+mz8iv\nablnb/4wsQ7/xCq0otWtP6ds296/ysCNQwhB4jXPHzZu7L7mgmWKY3uz6Yah\npmv71PQspT4Q6NZ1JpOynwAQCf2E7jZUgHrBriE6KEnJ+ZKdcgratyGtno9M\n7k2bhUxZdbRWQ8yUnljPVMkPFIBd68hYcwTg7iH7iivqo6ts+ekH9H9RV0ig\nM9XrKV74z+0Dd5wF9Lgmkij3E189aphjbJSTO8qx6iAu6SEbVSQiwouxf3U4\npAF+rM1I7V42IBVLIroHkK72BABdq8N2dov7p9QAQyDqAN75mEYrak3fRO6g\nbXHL\r\n=UvlU\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIDg/f8GMm8osCsrVzT0jItOTg2e04wF167jzjQnbOGJ4AiAZVsgHLI8e8/UXpQIvzaB3FfD0hlk/YZOuyZBceT0B/Q=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-4_1542995570197_0.012804746317107929"},"_hasShrinkwrap":false},"6.2.0-openapi-5":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-5","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","openapi3-ts":"^0.12.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Greenkeeper badge](https://badges.greenkeeper.io/contiamo/restful-react.svg)](https://greenkeeper.io/)\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you need to add `qs` as dependency to your project, and you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"1a38d4447765a50036871b408fbf576ff467c058","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-5","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-Ls3k6dPZY31AlPmQNxH9K3ayakvLx8ReU38ux/bzBKZki9EAKH1+a/ulITfMRFubCG6q0qP4fAOaJcko6LCUNA==","shasum":"cd840d2fb005cac6b78f10399876a28eecdb6fdd","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-5.tgz","fileCount":40,"unpackedSize":184966,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb/AfZCRA9TVsSAnZWagAAR6wQAKKURhw+vbxxe/McOd9V\nXWH9zvee2Iw4FbPaMFMlWRYjaX0magHuwQTp0gPRMAcZiN6uLRv2/yf2hRj8\nMc6sFI5hMC1DNcQNlcHnpB3/UHAvoi1jFRA7woBElTRRTxGHMlsC+3AQbWrB\ne+0lCMAalpv8VHk4XLGGAPLmRnpkfmlBq0AaHc21JVS9q2VT2TVFWLX5aQe5\nhajJ7hBf+OblPxdwLxva9oaYemqTr9J5Ma9UT8+5N4jZAqhPxtlUhq0tcL9m\n+fnYTWHQej/5fRUvnKsnk3PTuC/4wCQZFoakKg7W1WT74qHCcdy16xqhEpLf\n2iuA/OO2cjsqPpN8iEL7qBHvKuj//2zAN/tAUE1WRA3FXpOxJmBR6iVEzBeV\nxl9oobFI66vqTsi/kB564EEMF0phixQqt874iO0w3yIzE3ZFLGN/C+ITV4qz\nE4Vs85+YHdE12B87bchz6Ws81eSaTnj9bz0SAo7sYEYm2WoffAFXk1ki57aY\nNguMhLknr/cXsvOY6tsmVnxBJBG2xRlQwPM50+06S4sRaj/WXzeO9eZ9ojza\n9ZyUEkuOAR9NNj3gaeJMnbtSGuPSD5GdZGz1dd0mIKoq69vmd0d+9V7rfVP0\nFCOfS50KSFlNjmUR+0I/nttGN9gzDDzsyQmfVVbovV7CSB1YW4ppVEx/6TUz\nU7Oq\r\n=R4i3\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIFz6Blie1L3LkKnnoImayVChuTYOUyBEYW1ZKWT/8lX/AiB2acXVNn+lmBvlIlGFbcOu98m/0wsfmLZ34tAwABRylA=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-5_1543243736592_0.3992987426170582"},"_hasShrinkwrap":false},"6.2.0-openapi-6":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-6","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","openapi3-ts":"^0.12.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Greenkeeper badge](https://badges.greenkeeper.io/contiamo/restful-react.svg)](https://greenkeeper.io/)\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you need to add `qs` as dependency to your project, and you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"4ed5034d8bf7dfd2fd8040de00c9d5073b2c82e6","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-6","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-t9wJucW8AjrowOHAWIxp/j1DDRa9mFA0fxCLoDnrkkyqxSU6PoNYZZ6bZOs/NfgZeUsvlxJWP9ulET5K8l03AA==","shasum":"563b9d25b3febe932387bffa14e8a79d1c0593ac","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-6.tgz","fileCount":40,"unpackedSize":186078,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb/RYxCRA9TVsSAnZWagAA65kP/jEgahxtZzrHfuTmpqfm\nXDrsgl5N0SK/6v1AyDrbMZb0q1lPouf5G91umzL30aBbBE28RsCUcU08O7kc\n9I6TzNDRokkr8KWOLWWRm+EJtekQSckmROCzAv/KU4rWFW6VY5ZXqyZIo2eZ\n9NkGilBbRWcP0Rn/eik684l654jqU4l0xoqFH2ww0+gzo8fgf4i2FENGptP3\nwDk8V+zG1f0+dt23TYqxIwkq7jeGjEP9qIp7fqzPx3qkIa6aKm48ehLIqkEA\nzdAwMy2CIHUrlHKYLApCyWM+315n0RiLZIectbAvL7B4IkoVvGZ/WRzFeFOl\nif/l6sXPk1971UXW4L87LuEHn2BJvdHnVymv5yE2hwS3x/lP+dWTNJ2otLQv\nPc1asO7TU6+HweBPL1fSzX8OCsbD9/PULHGpsGsJhCw5f/HLLGYN2M53FaTl\niQXlU59wvcM6ZRjxDU6Rf6y4c+NkU/jlMCaMT87xrDyGmazQ7nv3rnU1sa+I\neb2I+yYukQuQUUkRB+9hyGubK5iXxhP/ysSUgdIhPF0a1gm29odYBH9cGT4t\nGo6cuUUjAylWnu4268TV6cnpfpg/KsJ3OWO5LmnROI1wYXZtY8cPcVMtjj5y\n2I9Rw4U9mLMjboA6GmVv0cXIO9RVApvyYLK05T75IefR8MusOikF1Bfq6/Qk\nUWlK\r\n=Mz/b\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCNBIzYv1s39LSVL9+wd3pAkMe+kHshVy6C81ix9q+PXgIgOxrtL2l8bS1a+VBOcCbKFnGacAOJNZfn33HVpCcJD9k="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-6_1543312945238_0.8990356608919536"},"_hasShrinkwrap":false},"6.2.0-openapi-7":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-7","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","openapi3-ts":"^0.12.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Greenkeeper badge](https://badges.greenkeeper.io/contiamo/restful-react.svg)](https://greenkeeper.io/)\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you need to add `qs` as dependency to your project, and you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"b62ddc630b914c4b76c7c4a7c9617daa02465812","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-7","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-t5gSHe4P51QTzcKyBY5ODt8CaU5XMtNtaU9diR9dHcO+GdvwEI7QdK/4cmIYg62/yzcao+ORIj1499N5A1YyUA==","shasum":"e33fa8eaea809f17eaff717bac0c11e2ed8286f6","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-7.tgz","fileCount":40,"unpackedSize":186642,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb/RnUCRA9TVsSAnZWagAAQaoQAJ1NU2GzH4Qw/yzlctLd\nKqn0D7X9CjqKASqxADSXFkI4o73uUS1URSWWWMso7zWmfg2iy8kXYd6CKqJj\n1MwZmVsOudOMXvIUaWtsNOGqiAK9/FRRzp2c6oa/YD01F3k/G1x20OtxHkyF\nM+obH8DMViCjGKH5BNMXAEoBc79MA+dG7knn5sAEBffP/oNE4zGgJtQMC+HE\ntDtfrtgjn8DQsm1JmAgmLoMRnF85ucrBnwFp8hCpBIEDDVlinuWAegZplnUh\nZXpEbZv+LLRcNJMiig9DKQwrClTG7teG5DnQ3oEts4R+fJ08MlQsedbfA2n7\ntQfrlcLtKBwIIs5ziGEuP8cL2bpoJJoURGe1MwNcQ/HEgx0wGwtoqA8ejkLY\nMuMt3/q0bBXbkOBQBFlUmu4/V33EeKavZPLOR4eO1cbuWnIbVjQg9ZzxsODv\n5SqYLBg4rfaVdREl1RTX9AfON/sF5LlacdOMRSQ2To7gmtfC1qXdpYhy77J7\nHK4nASTM/gBKZ+oIr0BhCa26lh79VFVOLR/cg3oRvGaEV82lryRsgmkKdrER\nkenkCtIfstpFj0M453JTsAMwLnRgw95bNKrU2FTWQP3YvH8h2p8svOaGg2ja\nyDWqmvMVMsC4Yia65StMGZRZG4uTdTdtFNbrmtUTa4nl7U5ScRgq1a0Hxw2d\nAT+G\r\n=S2ET\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIHfC7AgH8oqISo59nu5btxxmlE++Dn9lViWW8syqMdCZAiBt2v5Zen7m/88guXHkRyJQaPVWpO2p19Bt8CL7anN3gg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-7_1543313875961_0.2801384211006055"},"_hasShrinkwrap":false},"6.2.0-openapi-8":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-8","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","openapi3-ts":"^0.12.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Greenkeeper badge](https://badges.greenkeeper.io/contiamo/restful-react.svg)](https://greenkeeper.io/)\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you need to add `qs` as dependency to your project, and you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"bf76759f896e82dc08c39b8639973f9d2114e698","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-8","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-qMcq+Taie18+LGt3pYkEIqROA0+/5BGS4ZyqRO+pLyzV+0Mq7lucfE47owQATV0wJkYcNEJo/vBApMhiBFYXFg==","shasum":"7b5f937e87a8b13fac0f9d57df7971931fca50d1","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-8.tgz","fileCount":40,"unpackedSize":188964,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb/WxqCRA9TVsSAnZWagAAcpsQAI/TtwsqUCCGsknte1mS\n19BCRV2JK7q6Gto/Xl8BWFi4+e/WBPM7nhcKlru3aQAhm7SMwxwzkOoeP3ZM\nEzRgvsdZ3Cr2/JIahINVElmM8QTWIRxtJZjbolPsaTgomRli3I/zuZ9fn6Rr\nzRMbLJkc1C7vrL9jTq//BhY1aas4iKEU5wAUJ7WS24t+/CwFE1/jcQFgBm9t\nYmqwt7QEpsvxM21hnQVSNDc2gg9f6ko8FcATzmUBZisnUvthdAIotn8QDdbs\ny0tRe46L7MLMi+ABv1zcv36vUE86j0w25/W4hnxNbH7ReEZG6NKFaAYFYzyC\nE/HcM2trrljKfiMANilKl1021A0Inf/0jzELoCTBQ26ZRhO53aNRHR8T55JV\nwoOyaMqE9P/O6KN3WyNs2+tH9DrkMBf23shTyLVk7XeDEtagyzEvZJfn+D+8\nOlS6yCCwcDM7+hFlbsPPMvu84/aYWCkS01bK+IekWY7txfPM2ZSdDsj7dm19\nlHPZMpj7+kvS39LxdcomerbaylbKUTY5QWOO6Vs1OaZXXviQHdy0gYLgc32V\nAKtUJNYBSI7g2OU+ZONhC14FHqoxucog6dihMuF2J1Ub6K4XSfay3RBk0vpd\nV2DXiyd00/Uvu8zhwH0gQ7kiJAG/nBE2XQ82sxpK8uNFNOQIrgUdsE2/n5r4\nkAMb\r\n=xXfW\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIDYmDzii5oCMqmWrulRUTuXEzSnCSYywzVMlln/+YVsQAiEAra2q5FOcGyuc56azt3jDyrsouuKxLBTCtGyoJ7wf3eo="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-8_1543335017432_0.7537514816445907"},"_hasShrinkwrap":false},"6.2.0-openapi-9":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-9","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","openapi3-ts":"^0.12.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Greenkeeper badge](https://badges.greenkeeper.io/contiamo/restful-react.svg)](https://greenkeeper.io/)\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you need to add `qs` as dependency to your project, and you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"f65cd441cd404ab229c3b56cbce9097d5e028aca","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-9","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-Ok8G9VbnHgfdPW6/ZtIwbKpfOnVpiDoXJZ1Xq38MNPgdi/oCVIZPpol/+ts4urpPh7TTWc2Djn3jc1zD5Hb9bg==","shasum":"5e340e4a614b4ad275b0fd74047856def3d34524","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-9.tgz","fileCount":40,"unpackedSize":190030,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb/XdQCRA9TVsSAnZWagAATSMP/340R3UfBJXi2v1L5/Q+\nLjNVjCR90ErvrcCKDET/MnwrEJ5lhhVZCmk0jzAarOgPdao1ESARft6ApXo8\n2GtplI8WeqpKZlmXqUg8kmmiUmVyf3piud6UPJopskEuA1pvPAQNpZROCqwb\nipvcMyoySDBR4PhbGA1u6IGivhtupkbSP6Fox6eZ7SuOw+sOYesG6yFthPgp\neswoUMbZHCNSOBgj9V2iB6M8gCC2ZV5jtvvcnNWA4B7gfbZl/7kf15+7R08C\nBYOh+8zBmpQVn+AciT5Umg/+QRQ/JWOOEleyIUwwcxLQ3jY7ns9BMJQGAuQD\nb4UPU4DSGB+T2bEubf2ZDc65EDypE91BvJfuLcIzh+5UwOjvrsvc9KNV8Llh\nfPi0zw9LUYey/Aaj67V+14fTJFGCSQVCpdPVGTMyiLX8YCh9o+Bh2cdwgqkM\nbsbst+RSwTuUjw+3/CBW5pU3ExWZC9Q2L1qYSsbLXi+S4QEWaoArZo7rLKk4\npYIPmCON7OTkmD0zGSkoxHtXHMSZ9nPG73M5OGur8QHty7/7zN3aJEMNiYlL\nR/gxSJuzb5bwk0ruB1WDPEMUVYOyqW0iOXWMe+qABmD1Pu9ibm6RMqSTF4tj\nURnCIeNYaR31ZV1ajymbK0tKo/1+Z29VhpyxGKx0E/AmgyCVgQK7b76IkTNc\nITP7\r\n=ZAOg\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIEtfVamQ+AqqvLKZv/gDNMXQaMw1qWJA0guN3thFC1TzAiA3V9PbQ+w80lI1s7rwyN7t64xu4gfkXp/WkZKY0q1eBg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-9_1543337808263_0.7132225291161891"},"_hasShrinkwrap":false},"6.2.0-openapi-10":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-10","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","openapi3-ts":"^0.12.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Greenkeeper badge](https://badges.greenkeeper.io/contiamo/restful-react.svg)](https://greenkeeper.io/)\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you need to add `qs` as dependency to your project, and you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"d76a54ea3c62ecf5ef7d6223fe0de4153607e3b4","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-10","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-y6CeZ3q67lmZ6OxRZS04ZdN3Qc2CXZxa3KLsemDuxabUl6gP/SP/mDlV8ijkgqZb8K7ETmVqX+ggJNhsvlnKqQ==","shasum":"8af9e4b2b0e1950abc2aed40e4d327636ad64708","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-10.tgz","fileCount":40,"unpackedSize":190075,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb/XnUCRA9TVsSAnZWagAAH7kP/i4AaxWi99l5mo569T3E\nASntNMPsKK01whUBIAIqoRxdo2ZBwqQZhmpsnnkOXeT7BrHHAPbwJZ4CWJ3U\nhprYTtK0UgeLNSJ/G8fQp2nAtBRyxbOeXR5K7oVMhfJg/JVWAjbxceAA82Bu\n9ESRJw10lsZnkdoL3NdasraRu1NkwRZyuTqQ4uyyDhv84FHOKvpp8vVJWhBq\n7jQ5S8yUz+Kx4xGCuv4XVOexu9QR4Hx3eboUmqi1+iHcH7kic7Saqqwtazmp\n0Y8WtLGYwtX2afb3s07bfcKkOhlpj5idZSIGKrRuxI+t+dh9MaZzwoUr+ufE\ndGuki9nGtALZYC9y3BT0h8rGoInLQvEZ6++cGr5j2B5tbtFhygMf6U/Qq2Ae\n2orIKwnFjoYwwvsd9zh65erGRbmfIRwERrFz47rHJLME2vUvlQdTpdoUxL3D\ngHoml+BZaKs7Ah5t2nHFd3GahayfPPtsnMlLwGl6gHJls9sSrw1ZaSMx9/Tj\nmIbS3asxAXNzJGWbL7iQZmPWtlgvTFtwDfHT3gxIntACBOMHaSEeuEinvpIl\nAZlZclWLAf8dFVn0oOe7K79CBjIYgxDYkiOSOTxlsdTRrg6ZyLmYiapb8vp8\nrWAqhKwtI9n7taYmfM0ZI96Cod6qLCf9gEUR0aeUbCOO0xfTtkg+TB7OBrA7\nLrE6\r\n=LXj4\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDfe7Qo+56Z3mlFs6F0/1JX3Iip8o7O2qyo0x3NiPGkAAIhAK+25sRdlkOCqI8Fvye6L2b+IUtAGYUwE9YNyqGq89UO"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-10_1543338451945_0.19255647029865353"},"_hasShrinkwrap":false},"6.2.0-openapi-11":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-11","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/qs":"^6.5.1","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","openapi3-ts":"^0.12.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"9a710a768ed4702efd921200679bfd5db5a3a5d3","readme":"# RESTful React\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-11","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-dCLR3jtH82KTJE1TLH40C0ygYN32QsTumxbhQti9hfVbG8iCHwD3GjA657Hz35BuGoPYKEuvv8BfCm/G/ep+gA==","shasum":"a1911c92c4b1068b3bbfea1403bcc64000ce1915","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-11.tgz","fileCount":40,"unpackedSize":192403,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb/78WCRA9TVsSAnZWagAABkwQAJV1kBtksKKph1SRaFrt\n69QhhvDXQAyBLf9ctwXEP1T37Z0O41ZwbiJVNiQezJRiQ2ZaIqBHcuDfZFBr\np/sQlhWu60qLK9hLJj8tIDs23+Ald4X8gmIJengd1XU/xOi1nY6cyflGiEoV\nlD5+i135xfZ9xLCXKxgAoEYYTNKobPb/WbafI2+LXhfZMjTs+EYSdkSOItPa\nH8ihkMwOipjntNBRRM96CY7sRldbDCUxXf+YPXgFTqq+NDeipXuB8AbDyxDQ\nB15+Mo+suCrdG3IMfy53Yqh+GjJFIS1IuqGEjwxxG76jCkWpkCsABP13Fbli\nGKILFF8Cs9OFtA1CpubGDzXBzH5jQmh5qbCyEQg9MyRkgf3uNjkNxOvSJfK/\n2MQ5jZBe/yuTxAv8hKjnit7iPHja7SE59Q0LX+htzjvKVmPrHU7NoknRev+D\n5fxQXYk9SjsK8DGpznND8dlaRZipDH9WiOeF+WmcfwXTOMsqIznaYj5oye8w\nEFPuyZz/+GqklB/CpfJA3gNiMrECOYgOC1gSi9k2IN9BarBk9ZL8hsc0bndR\nM8KslW77NgdludI6wVmDmWbDmCiR9bILiipBdG5jiWLZQ2xIhUyz6PyWlsEK\n+ntiVcCiefmGRT1/nUIBW6YbsDICX1TyzgXgeldo+h4AEbWOqNSUCaua62HO\nFJSs\r\n=q4Pb\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIE9YRbshkjOk4fAUziODlgJezYD7eoyLjONWts92RfFnAiEAgNvz8P2Q98rJdqw/YO3+IzvVvP+2V4U9NgNOGJlMZC4="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-11_1543487253731_0.7297688449764088"},"_hasShrinkwrap":false},"6.2.0-openapi-12":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-12","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/qs":"^6.5.1","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","openapi3-ts":"^0.12.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"9a710a768ed4702efd921200679bfd5db5a3a5d3","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-12","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-BjGGz7bs/RlNT8IiUmOd8h2YLHKcmv9aUoQ4vNzafLBMnQs3o7PoxXav974XuoBrP9FDplIUvBzy8JewgnHBlg==","shasum":"675fb9d2c9977096aeecddd7102627e5aedc9cf1","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-12.tgz","fileCount":40,"unpackedSize":190987,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb/8p/CRA9TVsSAnZWagAAYE8P/jzWiGYaaR0bIxRjIEnA\nOY3MLJ4ncazD9ZwkPcwOEgx5JEIF25/YEkAj6AqyGT4MrTUTXgDLR5fxnzB3\n/7FjoE2I65hVzBdedJ250syLwyCU4AfQ8QTqMlwnyi0c0c4t2xXj6UnKY0ZS\nrgrGsz/swvJDYtTiT46V9WF61K8HxqKhSx7FSYeW5KQl0UnArAV29BXtHFlj\ndhpFFEO1cjhWHBAez6goXDM4ePqcI+sPtfxntEl9Ss+mg8dyWYQ5SUantrHE\nmJT4DTloVp/zVbCFwbvqc8rniYoa2iifcp2+GmjJn4PABylHPrBkjbc1KY5i\n/6eAzHv+I8IKPHW9Rs66ON5SRd8K7SfzYahxG/avbGepq4B62uu4Tkwq086H\nfSszXN8LdhGA4hr4PXCR4kY3DHtZLJqj/EEqsAoYUtKyXDUpa5QEGnC8b+JL\nBupiDsdRaXYWWHzGAF3tZjMCtLenYjEgWhuS6RoILiQor/E5UJiUsuN+2pcF\nXTxskq8RdBZOznCYYk3hC58litmePho6SIt2X5axac3xQRhRS5LroB/VSDJG\nSiT9Lw6MTIJGFUb5crnbtXaBmTS85Wx5rowJ7OswsFG4jEaj9Hke3G0RyDu3\nBRy2rfqpG1/wIkUBgNbRWCB7WAynaKBlS3rYZOiP9xPjZ5T+GxeGVvNnz66N\nU3p5\r\n=p0hx\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIB+aJ5VcMEmHwONROdXOzn8V+YGXizH6hoHTCdju62/2AiAXpi3WmAOWFG23ueET1IQylhqWtXLycARJBhr1PouGHQ=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-12_1543490174632_0.7499563518656673"},"_hasShrinkwrap":false},"6.2.0-openapi-13":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-13","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/qs":"^6.5.1","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"c9d3a8627b48041daf91fb084554b5176a8857f2","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-13","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-YZ5y/oBF6K4YD1lzKUwPUGbx53eUCFjztVggRCW0cD/d8PWz755XLkeXivTamatoCu0fHBw/FvtC5Pkh6JeDgA==","shasum":"e0afcf66fd9174fc49fa55f5c3768d4387217a50","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-13.tgz","fileCount":40,"unpackedSize":190774,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcBT6JCRA9TVsSAnZWagAAo3sP/RZnbeqZ/le/1WLXHD1y\nM1/tLYnceLaYi/R4gH6Ja5Z/uzrO2kB6XI2aVXn2hkcGa0h7KW1XVrxEDk0P\nqajrt1gMe9mCgIfEb4Hjre3eYU/BDslJQBak3ytqObMefP3sWaAKWFd9wuf3\nDQzv1ulktcsruym9XHPsNtuxqRPVCojlc19aVXxFENTe8HfMAM2K+3/mfDQo\nKYifU7yrWTixNKeNiFamqZ4JcVuCRYNlrYI7vdj7CTmHofTxr2jD7+uGhd5t\n1zr8N9q9rY5QsylYLaIu1+rBMXNOCHOngjG2rdXgjcE8KmpytMRi/XR0aOYx\n2iY61pqes5+Apr6qohffkJAIdmHPGoswmN2/RPdE4SfHybs0K/cA36rPWuL4\njVeGgFtoeFa8VSKhna6YqHVr2Weolie3e3x983goCtVYuhiZaLgA2TRA0pO9\njKNsE947Bxg74UTw3DTacv7b0WqXgOGqTgjxvDfY7TxyBsxPf0hXUFxvUyBS\n1FWlIv8SQA+VzlfqztHph74LtD1JmK1wD/D0S2D274Mf1ifdTan1wziUi31F\nNzYYUpsJvmncsPNZhABQtnIXflvF8GWmq3DW+NEl/fOpRMnvHDFxDHue2lnd\nQRXV7AHsLXnPQ146YW0FXXbM034NHknzNVEmRo4M9A6vewGfuxGadtc9PWJC\n8Njs\r\n=g83M\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCID7XQf+nG32gyyiAg5ut+bmJmQI1AHZqWo8AIeZhzAO6AiEAlj81OzY3HRBos+IJMICigP7Uq9MgS9g5mvb9nZYovwo="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-13_1543847560776_0.9380753381851858"},"_hasShrinkwrap":false},"6.2.0-openapi-14":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-14","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/qs":"^6.5.1","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"c9d3a8627b48041daf91fb084554b5176a8857f2","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-14","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-wIlMGG3gKzdq8vcGg6eSq81b7WXH5bxsz99Z3rEgAzSpHuyMdsA/ZfSB0PcrC4a3qULQmdlmBj26BViqhaa2Bw==","shasum":"0992d053858966237bb96ddb273a8b4097309852","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-14.tgz","fileCount":40,"unpackedSize":191637,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcBrjLCRA9TVsSAnZWagAA0hcP/20mQpHk/02pbjZXLbOL\nqxdm9Z9XttWMTMsKykxek/TnnQ6pecq/R2F69mx3rzs7znL7cFAR/rIB/GVH\naimePvsCzonGELiZ41TFZLTxjzvrON23neZtZQHbn76IuyoSAwYsh7RZtUKI\nVSaIB1y7rKPVQLPOyEpPg7MkpucGAUvMHlXanfKa/MZjoEr8mdhE8KNj3/vG\nsxwDl+8faKa1W1W0JNxESikQI4Qdd/vlwto9qNtLOEveRlCEgy65cg0jTX3Y\nvDOcQDAdqm81VFw8ozsxm+jIhQ6vLQEDxVU9oTb+lvtWX9p5KRSheFeOPZiE\n6hqavypsSNLDXl7IjQAj/WtrkkJxXKovsI0FegVLkrdH/uOBtrZmm4NWTiq8\nSs52ci+m6xa/Y9jFSGHE0rjYE9EE/XP2x1TZrJich39hbgRdmo4+x6ZReaq+\nSr7L7U3DKi8Ji1TDDBteWmgr6s3Z0zSimmn7ytjhRRniW77Gdm4CO/Xil4Lq\nG06zeEc/LrEhbKPmkL6wqgB8uscWk/Tk0zmNfgtXZ6q9+mRLmTYSZ2tSZQjU\n58PEK1THu4U724fBdQUmGefCNS7bjKX0EYLrguVI0A5CeSAgpCek0U+zmsMy\nPT3Njg6YYROrcSkED8BdTvSTRohKqC6Za83B+vvgkHsIWyxIqPgt6RvP8D+w\nN9ei\r\n=0Hwe\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDtpAVeFJEBzfLt5tdaMAC7bidE4/DejDGcAK5B34QOWAIhAKwJX0ni+dD3Hz+lxm0o0PvIKrJxWPx9NkBtpbcHova8"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-14_1543944394961_0.11323810683262758"},"_hasShrinkwrap":false},"6.2.0-openapi-15":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-15","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/qs":"^6.5.1","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"c16fdd23ab56a4738ac22ea640c74f701b3787f6","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-15","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-1uaed5uQekGMgHMSrbPVdKvnpC2A02NkDnWfi5oL0GZgYHxsg+GPeWz9eZaMgIYahU9ZVuNvGsq2e9FOoESFsQ==","shasum":"869a256851a1a782f19a114deec43ff3bbd0d5ca","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-15.tgz","fileCount":40,"unpackedSize":193328,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcCkRZCRA9TVsSAnZWagAAqJkP/jv3zvL0peSJ8XqRJgcJ\nn4wtd9GTssYCcbJzbhN4v27gVZmRe583EH7taIWVqpp50/ZaHQ90uZ/EItu4\nsLFK1O3IGjJcbq+uPfDI3NsVlxHKZRHAFPLPQuDf6oiraIoxgCkksNuqcbai\nsRrWejnyai9sFD+bmUwqildOdY5Weu60rZBcb2PozKB3eSwHDk8/b+jzn5Xy\ns9PsCliqon2nDq0clrYGJ6YD3Dx8lb5uxgocHxamhtm0tbxo9dNv6Wz8FP3r\n0fWWjCYhbKrFy4zgmul9chtvMn3ojWbV5tOwVkOK935elpNr9V6FhWSXK7xO\nYgzf40snAtGyoEd9pip8trzhFdyFaEpZSuuZO/pTDXnr/5lFfC07/PN8ivEE\n++l7IkoIUydujpsEiO30Ife/gC68+HmFL2djjfWUDt0xdTXQoT/kaiTekb/p\ndE3lzhbApvdFIJxOUnfR9n04LVBwbppJ0akAOMbVeVOtiL4cJemcOPlqnSpq\n9XUkmFTVB0rB918Ac0PwBD3cVVLwZQNAy+9jBJ7mvrltQLuHo+HXwt1byk86\naZdRA14VCbsqXNQS/bywNSIK0B6KKh1zgihqbuYn1hLQYB8KY7e9SHoX4ni/\nEaGwpKrr/4NDxrL+2j9PICNHZXq8hh6FEHTUX7LkiqAdzHBLnBA97gwj3V7g\n6BcE\r\n=6KLq\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDPb1hp/CKN4ZzbOzXLkFdIPYJt3MAr8Avrj+Xbb4yxrAIgdVXeia+Gjeb23eA3xZewTptCcTwGDHWuO+hb9t55fKo="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-15_1544176728231_0.6932749199595372"},"_hasShrinkwrap":false},"6.2.0-openapi-16":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"6.2.0-openapi-16","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/qs":"^6.5.1","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\n[![Build Status](https://travis-ci.org/contiamo/restful-react.svg?branch=master)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [`Get` Component API](#get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [`Mutate` Component API](#mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [`Poll` Component API](#poll-component-api)\n  - [CLI tool - Code generation](#cli-tool---code-generation)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs at an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base={HOST} somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Use the lazy prop to not send a request */}\n  <Get path=\"/breeds\" lazy>\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/* Composes path with parent: sends request to /breeds/image/random */}\n          <Get path=\"/image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n          {/* Composes path with parent: sends request to /breeds/list */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path accumulate based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [`Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [`Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTP, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [`Poll` Component API](src/Poll.tsx#L53-L101)\n\n### CLI tool - Code generation\n\nTyping are awesome, nobody will complain about this (exept if you really don't like autocompletion of course). But, manual typing is boring, long, and error prone… Luckily for you, we are lazy and really believe that OpenAPI specs should be only read by a computer (not really, who else want to read 10000+ lines of json or yaml :thinking:).\n\nBref, `restful-react --file import my-open-api-spec-3-x.yaml --output my-awesome-generated-types.d.tsx` :tada:\n\nNow you can import from this file any component with the types generated from the specs! Say welcome to the autocompletion and say goodbye to swagger :smile:\n\nIf you don't want to rely on a local file to generate your components, you can use the `--github` options to specify a github file instead of a local `--file`\n\nExample: `restful-react --github owner:repo:branch:docs/openapi.yaml --output my-awesome-generated-types-from-github.d.tsx`\n\nNote: This is totally experimental for now, so if you have any issue with the generated types -> just open an issue (with the open-api extract and the restful-react component generated/wanted please).\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"02c44ac9f2a525b017b76cd982fa98bc68ac5935","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@6.2.0-openapi-16","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-lIJgja9lJsVBDubvD13zMMkByS7qEJmRbiJln6eOLykGtrx7/gNs2Z1y+tb92D0B9585MvPZEkc84AHcM8M1Sg==","shasum":"e167040c41471f10ec4d47d4a914c75975e770cb","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-6.2.0-openapi-16.tgz","fileCount":40,"unpackedSize":195284,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcCkwDCRA9TVsSAnZWagAA5MMP/i/Lesn6ueirKZ6P/RYH\niTD+ocWcHxQ83FpT+yb+xnZJT5LxYdoCaLtC6sOAPHdz7GLvrhc07TWFlQs7\nBpoj/7lz6HuMwlNqF8jmI7V9IjKS8Ef9cdmcWL+GTbQNgBQVE6Ja0iYm6LFQ\nam8TqbwEz+M2ltyfjVMy1WXEhmPu8lXAEpbSA/+4zoflRrdCuWfR2ZFCExl+\nDIAh4XwPF6C477y5Cc0c97aUUg0jdNnjFgbWsMVTOpSocEstSYik2VxEmZhg\nyOJ56VTR4G2X0mhFSlHHhbIWf9nBozm8Lz1pU8dGaRdYtnEAcuHjbq28SEWU\nFXSdrQoTYWPqZBNm2Zoho/W4L9iSE9bqpZgFlcM+b4qHdgif0Uh1EbFxsTpD\n5KL17FasK5nh7NWlcSbDrMoJK4P63e2ZSc9g++pwDIlZFu7B88n7y9R0fHMP\nAYIwcs69oYOClCc8NrYpheFDytA5DglJt9t8dnPjsYenDoNrOi67RIcrm+Jt\nWEoSSL4VKD/KfvZ+hhCQrKvegRaNzZX5MjM+t4NbxKDbSR7fBRs59Jd2RWHd\n3BUpP0FEMtUUgv+WighrsauCovQVEvmCz0OtBdCLyYSlGJVEZuzyUygAm9nL\nbfjSDeLNWx4aYF30tezn3tUHxMBxJLHF3zPatheALsqUUks8f999bQJMZiPT\ntw78\r\n=+fIv\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIDDuDQDqYMXlC5LbeMUDcxidpNqE0XH34/qegw1yev2kAiA7ZsMTOF91hE+66460Z/CaAmS5KTK4un7cKaURQKIjUg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_6.2.0-openapi-16_1544178690409_0.7545018384246223"},"_hasShrinkwrap":false},"7.0.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.0.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/qs":"^6.5.1","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"180a5875fb1c3a9386acd413fad3a1870aa7a376","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.0.0","_npmVersion":"6.4.1","_nodeVersion":"10.1.0","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-bXahRO7yKC7P2DkX0S/hadw2O7ZMUtYjK42layK6Y2LFKoc8jfE7LZ1PHweof0VAodG5l1utwXuen5t4+0cM5Q==","shasum":"d0de891d6f2272813c1d96e4b6c4aa45117eface","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.0.0.tgz","fileCount":40,"unpackedSize":197594,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcCl6UCRA9TVsSAnZWagAAO9oP/1JH7FBpe02GdVyuhNtw\nYruewi0wwLx1HQ2Acs465yBLF9J2Ut4qGziVN5WHYFHT5n7F4cag1dZaeDFf\nQ5jkcOMU+5HZeHEPqZ5sqmZNSdEGbMF4T5AJn5AHM8D4vxMaM3qCWVuYqXHJ\n8nDh1Y/ULtQEUasvgBT/DQNxX9375ac3KOD6rSCIENu/uZedEe25Zh06jCIE\nJ3VYJi9bKbu6zgIo7SCl9nZSP3txE1K+17tMdZGLPH0MGnPM1YqSUAFepYZC\nWsjI4FMBvsYQzxlzyJ0BkP+1atxt6okHunah5RfFyNnAAThpxzIt4/Wz3tBq\nf+z5TLRthF/A/6XxhCmFyfWSdPD+UA+m/5Sdz/DXgyKPx1XbGpOrWopPEMtY\nV55Dc3lexle83i0+iqY9p6+CRwKlEEn8iSMvipEh9O5eFBqYzP3oIsGT5mbY\nE+iADusL3+TOeVdoM288U8KowsmIYjWE8Qafdz8mrI+4ZWnZxedoPO4SnXRU\nMGS2MXpiVojgebeEmgYRWVZZ1VHU5s8iUYL1cRw4w7UYIbE9gaAinKUHJSzo\nSzKKNw1aTXcUCJWfEkfY2fhOAaJjcBPKKhzT1a4pIecSpyMoPPiNvXgP3xS3\nl/I1j+gbgKzJDJBzZhBVyBGJCHxxUZy+018tw5y+eYMeTBhxwwtB2Yg6ssG4\nvoKu\r\n=9Qln\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCEQqP5pfvhXjSTTwt1N3NVVJGCAj6Sys4/Gb4JmFrSqwIhAKDdldazDkg7X7KfKyQDAvI/KlJUlN4+d5KAGcUcjFRI"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.0.0_1544183443780_0.5810467910974138"},"_hasShrinkwrap":false},"7.0.1-0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.0.1-0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/qs":"^6.5.1","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.0.1-0","_npmVersion":"5.6.0","_nodeVersion":"8.11.1","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-XpqrmalqSkTNqnTFAd+GWYEBNAWWmYlGGCxRdhI2GVaS3+SuumXzOQheafi5naeiF/x2dFqfPqtliyEWfJgv4Q==","shasum":"5d0bd666b9a986160245cbee9188ddff7e7ea080","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.0.1-0.tgz","fileCount":40,"unpackedSize":200186,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcCrHxCRA9TVsSAnZWagAAz7QP/ibfYELRmulYbl7zGOJ0\nNVHjatcToU/L3lgHGrZjrCkpeYEnI887ShL2RaBt8KTa1OyiOL/EiMBLmt5H\nm/Ar6t7TDhx8A3RC1nMNsjN1z1qW6PZP05I0zaUWpQXMQNUDe4/sYiGBddXj\n4XlWUcNeqX8Qn2/I4JTn4NSjYZMG0j24vi/w96jOdS62c1lH4WAL9nwI5izS\nH3kuRE4eve3WeIdFkggj48Io6SAgTE+f1whdbq9p2S2KSy6r9Xz9GvrHszi/\nPaNUqqH6z0vwQs/4YEU8sWQVz9TshDYqhJXNS8JEhIxLqqy13DIY5jVTgxyJ\niPmi7xm5uGTWstT2VqRqApGq+Ge+F3y2a7pN6DdRn69yaeEgVSG7VWvsvoxJ\n3gRBOSiPWdqjEDvatWMJKictX0NWcAjf34g7YdSksO+Mb0tlsHCJ8Kbnpmfa\nPYMg8BabSRVOhVjrXdtUOP+piy0vEBCl2cuncfv+VOGarcxPeOlsqHNHPMnF\nHQKEki0CKD29QDGDUXXB1dEoYCM13im9SndX87NpdxAblddHPoCore52bNcH\nfZWgIP4XoOnBHgFs3wVAUyGUEKipN2tWURxRsNWz6+iL0uWZ7UKctgbaU+i/\nfimlECR6WTyWFzDIIzFTeyR/bQ7gHJZpwzs5sGsBf2OI7ve9fo5+9PdEhpqs\nTXb9\r\n=04uF\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIDkrSc2YU3sYtKV3Gy+l8oFHPeTXo2S4oC6OkcuLe8N9AiAPKE4TC0tKaoO+vAH/xvW3lXWVIiTYRQx++ExM99bnyg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.0.1-0_1544204784730_0.3407558246221478"},"_hasShrinkwrap":false},"7.0.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.0.1","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/qs":"^6.5.1","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"c0b6e10765e78a78e1ee75c4d247f560d0870433","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.0.1","_npmVersion":"6.4.1","_nodeVersion":"10.14.1","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-eMNJxhZ+t7ldTcIK35P4alosZE0JZhdf+voVIGel4mtiptutwL/ymQH3RcAya1VQdE1zQyLdIstnBDI32ssBMQ==","shasum":"9e7132d5576f5182b642e65c76e73bc9b8177cf8","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.0.1.tgz","fileCount":40,"unpackedSize":198018,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcDgZ1CRA9TVsSAnZWagAATNIP/R/Upor8rSnjXklxGRkE\nu9cpbOG75XQY0SCO/xmp2uFMGXkznBS172CKX2if0uwgm0OYe/lW+p8azIM2\nMLkPJh6lvGpVHKppR2Tl3mJb1O1ltdhlvUrktgRW5qpsxS+8dHs2/+AxUS5x\nsdVTxQCDgAlj5FAN/yjTY9qBVrkbk6FtFjRpwyLO4cGMyoAI7ZKOXWH/UN/5\ne5TdUakeT5R6QB2xOGx/MBCJEfLLO9KOifZ9MV8e3RTMUWgG5tPut6KSq6ND\nYQrSsB9+FWpyXtiCxCpPhRzpzo6/Euw0YvZG8xe1ky/eu801QmFww09VEi4L\nGbn62m3UFnRMW7UBDZ9TVL+WbIDTKgHNBsuHQ11OQVNADURvdNnBuxzaHy4n\n7auH30b4pe/wlWeiRd/TE+xUldI9er5FquopWiWj1Aq3RXalLvMF9d4TDj24\n82jqE2WGtcSVYnkYX1w7uYmls7yegEyLknLThFQ6/6l3InDGfr0whgG5uzP2\n6ShwASeM/dXxIMcKoDjOPKWMFhrW5TjrAgxrlxRLgi3oMz+E19lde/vxhSj0\nFT1ECUEqBPbxMm+VMyCPNYVGuL7gbs9Ofx2xvJ0zCqyjifK9bW+bXOH0egp9\nFIqQc07qN+jHc80P71BGpWa53XEiLWtDfAuhXkAXKJGCJ2hIRWn48YDQ/+CM\nLFSF\r\n=lSWZ\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIG3GnGJ9LAEzCUDh3Ax+DjlpH+olW2j0nREAuNVW7OOsAiEA7vJPVIULqdVjaGQGQuHX6inTF5fpZ5Q2KpMSK2Qz1JU="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.0.1_1544423028091_0.8322991491115166"},"_hasShrinkwrap":false},"7.1.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.1.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/qs":"^6.5.1","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"e465feca4d63dbc11b5480674413eb0a4d50d4bf","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.1.0","_npmVersion":"6.4.1","_nodeVersion":"10.14.1","_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"dist":{"integrity":"sha512-cpdDpgUeajz746wXqz8QAgvxE8iYXgWGbVcEfOnIs4aCdB0dpTFR7O1g9JOBUWNsWFMRvTGAUyFXY5WJLzmWGQ==","shasum":"47c3b4119e6c9650d714432384505c1383c5243e","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.1.0.tgz","fileCount":40,"unpackedSize":199642,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcEQ82CRA9TVsSAnZWagAA7NIP/jdUkFBBpw75X6vruKd8\naN0QsKzKtcgIM+CkDNunhX2+5JgHds4Xm01ZoJUPOOeUIVuWrnGVLEV9+Aau\nCPwC8f+M/e6YW/Z29kfKLeu3GzHmcRzJ1dgU9exvrRQ1SBhE+CEzpWLe547G\nHOjUwf8IyN0gsGmbv4vUuoOVirb3LMC+RONnVIQxelmkKLABUMxAWZ5zybTu\nYryjvPFe3QZEVaqaY3rMIbRRArrTlNhV8LWevWMRwT7p+0s9Xezk24dtnNXO\nlWDHACKH81yFFX0h84nbjRGLXNa5qDzkf7tPmT2s+9h4SDk937sKvnQ/blSb\nW1w1TH7sxjAkWOobPWlsDY0GewjCQJ9olxZkRQA9F4p2NFOrH8IT7D9p9T/+\nOcLT+S/tRLHMHfUwBpP8ztG67ivBHqgbYSxA0+uSsH/62KXZ3I92nT90E8pF\nTQnmcdAjNRuLDQ/HkUVxc2FkpzTFrIPjggTzew3lPAiB8kzio+2yzG6sTkP8\nhFHi0NcqGLNUGI+3ldIn1L23e47yjnqFG+XmT1HLTkP7XVaP66nUoYZFJ/Lt\njPFj9z4PX9KtYTSo+X2Fq4wfu9DAxw74Vor5zTnrQZ4fvcHWUiYHm1Wtmkh0\nF0tJb7M0Bass50gbaKvw5ezIWw1ZNYNNdwH8+P8bKWTN98z3rmexYvwp0u7B\n3rL3\r\n=jZvC\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICzVHXuUNczJSgKfwsqEnVoXUpqABjmsh07QSw1iw7XMAiEAn2mWfdvwuJCYRfojpi1WAmMcqc0+enmUwFNIOhJNfCg="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.1.0_1544621877258_0.874892611098937"},"_hasShrinkwrap":false},"7.1.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.1.1","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.43","@types/jest":"^23.3.1","@types/lodash":"^4.14.116","@types/nock":"^9.3.0","@types/node":"^10.5.7","@types/qs":"^6.5.1","@types/react":"^16.4.1","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.8.0","danger":"^4.0.1","doctoc":"^1.3.1","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^23.4.2","jest-dom":"^1.12.0","lint-staged":"^7.2.0","nock":"^10.0.0","parcel":"^1.10.3","prettier":"^1.13.5","react-dom":"^16.4.2","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.16.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.0.3"},"dependencies":{"case":"^1.5.5","commander":"^2.17.1","inquirer":"^6.2.0","lodash":"^4.17.10","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.4.1","react-fast-compare":"^2.0.1","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"gitHead":"d0e05498054bbcfc89edf0078374e29381c7ab1f","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.1.1","_nodeVersion":"10.14.1","_npmVersion":"6.7.0","dist":{"integrity":"sha512-8prgtsfKPTVGHqaIZLTXaf1mGIOgkVDsK9g+Dm2FkXXHwMkBmVIyY4NJjoM3UsmNscXKEPTKrSOiXKoqNob2gQ==","shasum":"03028b3853e4d818dcdeb88bdeec7c1040048fb0","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.1.1.tgz","fileCount":40,"unpackedSize":199997,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcVbVLCRA9TVsSAnZWagAAM58P/2sANhGhlt/QPOaagywb\nHw2ek5fnVQtv1wyKPrsqhpPoNm+nMQObTbPcesCsfkQ/Sr1ZnG+EJPQT9KRH\nqAKP0yNnzoMLQsgz0/u2+Q22ocuOgs106xiQZSTNMm8xd4bt36xN3rH6rJBi\nLUui5Ekv5ErLBG4AFppDV022llksjq9eFQ046QQ9uhp35Pmi53muJZPK1DPw\niUPFTU7MQAxDy4lNHoCeF4Vs1K+svfnoJMqD2n4FF6KgvMH9ySVqeFSboVh+\n/oKQnJE60tEYqYBeu2fxjsc7RMkTCbSZ0B1hudB0g9DdHXvfA/IAe+jHHtdz\nefvU4EVVD3KM2YS87f/kSk4C4Iqkl1gL0pRi/dydtkdC3XlifRz0pIucCMAk\nUNVbTueDyWZacCdHtclv86rKuxXwRp/ESqXda2H6wtszPgfBTlKkxFSEZbTh\nFIh4znzPGPHJu+g96mYet18+aAcH4krtMzfYBt8XtjaXGKH3iV8aOPL0SJ8C\nMKU54Y6c9OyYkt8zCVGqv4fERmlBDcL2tWF/9RyUZnGPl3nEnsadvHw97r0i\n12noqlB6QlZLkW6x0Mt/fhYUijRPDEMn4ECHwCqKOB2VtxOg39jW8oR+jACw\n01Y/EtCaCm3WCUpLcFmFkke5h+LBWdMSlTMi33F9o1fgkQ+xmdRZosiL1ZF4\nZEDM\r\n=sdU/\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCUuYPvcKXigXnbcmCejNqAwM+TxqRKzqsmVCXOWm5fVgIhAImLqK5AcH0CLdyG8sr2rt8NNLOuz7QSRHMEot4IeDlu"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.1.1_1549120842743_0.4262066443025647"},"_hasShrinkwrap":false},"7.2.0-5feeea4":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.2.0-5feeea4","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","example":"parcel example/index.html","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"^1.4.0-1c795b9","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.4","react-testing-library":"^5.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","typescript":"3.0.3"},"dependencies":{"case":"^1.6.1","commander":"^2.19.0","inquirer":"^6.2.2","lodash":"^4.17.10","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.4.1"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"9d413465f6fc43282019805b95c7dc77c539dc7a","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.2.0-5feeea4","_nodeVersion":"11.8.0","_npmVersion":"6.9.0","dist":{"integrity":"sha512-HSyCQiYolhvxM82YdkvgHWfRbM4Vs6xr8sn746EaoH3xPntujZNP7tm/FYyXTl37ECk5XnueuRROezIsWqLmww==","shasum":"24bda01551f5b9f8b7cbabe83542f9f6d6e2336a","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.2.0-5feeea4.tgz","fileCount":40,"unpackedSize":199583,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJci2w9CRA9TVsSAnZWagAAKZUP/j9dP7US4t4ccHj+isAf\nMSzrm67tc11vRqKxPXJOqeDTk610I6zI1FUeK/u8jqPRVvkoCxIbm0hCk3XL\nmFnpBsMgg8fX+x+/0Igl5/ZN7IsuL3vN4UtFXny+a1G8b35Krh8FFR7OSrLy\n+7j9fOS/lPg+pnMdB+edYRG7QZTS1ApwjRauAymJ2LmnjPbYeZdpWHDJGmwa\nwLmOasHwr0ZMt19zjHJRcCSb9IQPwgTWLyTVV86jfUzgHMKktc1pa+sbIYxg\nDwDGcZUVLeh5WhXbb6/RXB6ISHigtmQNT4FDdPjlBCGmlreBaFVhEACHtWEo\nZIe2yyU5A8Oz6n4/8wuUiCcD4WwFLg1wRNFsxMM0ohu9t4u8MDuRaYTat0JY\nNPVdqx4puu/TBWBgcN6W7eLKZW89FKnBZIzXnvZTzJTk9Bum7mgtsjWp3BFi\nykfTG44YlVNFGBFQXRMA8w8FP2ncBr0kZLOtr0XL5JmLBiUHfZEWuJyE9EE7\nTmBByT99t2z4WBZuOe3/6xIlcppdNz0h93xyA7JewiYJxZhrT2pxpqiLrBJN\nSDU4nnUt7AyE4IFn0cXIxbFuZarIMn8dNN3oMqyzYcVJwZDV8GCOtDvbtAyd\n203ZPGl5uHgfAK0ifV/YXI4GtHuDSRCeU76l2C1rkcsw2wftRTg2HJioerz0\niY/3\r\n=4qKH\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQClxsSyZ31aSzTPHcqvuDNW28/Cwn4y0ipIX38bj++BWwIhAJun4LDrh5oWKphfwfo2XMaFw2T16kxVC0Am49fh8chn"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"stereobooster","email":"stereobooster@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.2.0-5feeea4_1552641084570_0.5790381546855874"},"_hasShrinkwrap":false},"7.2.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.2.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-testing-library":"^6.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","commander":"^2.19.0","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.3"},"gitHead":"408e469a9fa7778cce7302c380bdf9ffe6b9821f","readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.2.0","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-4yW9wUjGq4EthoIBWmloqRL2lzrdWHKuQzlKTHEP9LoM/bbPzxfM0T6UF03BP4d+9fmo+xLnMzTrqg3dT8exHA==","shasum":"9caf0dbed63c5436a4f4962fe229f6a2b6636c7e","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.2.0.tgz","fileCount":46,"unpackedSize":223915,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcmPFrCRA9TVsSAnZWagAAvQsQAI/1fqS1lMlI+x4NJez1\nCCBMjQI8KWFy0+2kFYBtwtVcRnqJO/lGVWFXdYYe0t3y/EZfBkqGQDeFBgtv\nzAK2wSu1490/mjn6gyABSp2dapZCxDMLphDgHhdXKIUfSpGXUrl4Em+ta8b4\nIlVTSwjawEW+kp/n8FJDQks9lBBd5D8ePp0vLvome7in7jbESDRTAL1e0/Yg\nUaqUVeYnQ3Rp+fKA8KePAYVCCaKKVHt4iybIFDmgk+GMiujIQCTuCWNaf3nH\n4c8J4ZDhlUOwPYvfxwGo/p3QBFqf1/cNF3TMnQB1LUsQKGkvdA3ibt04aRo+\nrzLGhgtfPqVigh3sfgBbzzzi+iSLgxdKTvMwcJR2DhKMbMbIKVm6N3tg+5eH\ng0t6adP9Y4tfOIzA44GEyv/nB8npuTSvaqyNc1bW1k9pVVdK+RuCKhfejD9r\nxDEGnve/n9kaNNcQ3rrE5kK4lyHDYh+68irJy87oCu/ZSEfSYKTqoiwL+PbZ\n4NC/OzGG/znJK7cC3Wk1B7mqdIkDTu9UDKat/IgdAH4XEA+cuLlmbqWO9erU\nxVf2WEe668ox0sNt5DNAaWiwgG4rA/M8W8Z1EDGvMPEncKbiTQOYLU3+jv2U\nuoPIVBIrxZvzouLtRL+/V+YEeoA01MnfyvL23ijTqYHh4FbuUuh9ZMKcWLd5\nym9z\r\n=bdFk\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCZ+zNhuLmo/dAbJ2FrNck8X/Lu6Y+F+6nb3gZ8quBlDgIgA8U4HncOcaE/6TQPoim3wEgaA5/FJygt1yI2onxeQUU="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.2.0_1553527146954_0.26648848364020683"},"_hasShrinkwrap":false},"7.2.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.2.1","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-testing-library":"^6.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","commander":"^2.19.0","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"gitHead":"6c85a6d2b6aa0a893879cb2a21af47a541a3fb01","readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.2.1","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-ghkij0qbeIoNA4xXPDKY/5FnGIM84TzQ9yxWmvjtHwZtPaBtvoyoZuA2F42OhDBmxNpaWouh9s4m9qa85qatDw==","shasum":"b15c71bbbc2cbf80ba46174b6b06a39f33d4bacb","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.2.1.tgz","fileCount":46,"unpackedSize":225767,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcm0T9CRA9TVsSAnZWagAA8nIP/jWUg3hDGEAsw53dR/Hg\nVymWG28K9cuswoMU5dSixy8FAbyHveIpxf+of5g1bvOx1Lh7SOx5VLvhbihv\nFGJmF6PMwP224o39iT8aCWEjMNGTY+DiLVlW6DNc0tWbWC+C4r88Jb1ClEcT\nvY4MXxQK1PFxp0aQzzNIDwdajqE3RguGMRUQxhk8HMtidNwhNU2ZQXLfvEt3\n9YWa5t6JvyInVIsyLs4HMhciU2D06DGsNkbz4slf/yvXaNJaq6xuBKxfTKWC\niWOivnKMouXtsZlrHXfY2m2xHOt4/qKhKUcGBORvRA8P0/GJLd6esT763rpi\n7kXJPxlvYhitHSYVyI0UWLtU6pNr4/4uEwnOgVvdiwVvZHv4j6ypE4ayLXqk\nHFQcF0B309vgiR1zxJarjrKQw30fV/wSqak0JksKH+2qIhUEI6me3QLGFEfZ\nMVhqpzrwlEAKoRfyzEYyXAy8L6e4zPhFc3TZmk7+lGqEmL94PYe0wwNlfewf\nycDahBRj7lg14q9avmIIw5yUeyDcjQv63vsDM7OreJgo3ORYF9RBS23aTZXz\nx0YqGkvRIkYxcYl3AvwbCkWcKbDn+7c2TffB5p45IZ1mzUJHmH135YdwfGeK\nkEPRQWgq0AG/ZEEUwYLUstilItkwRjapRuzV0Im/CwbqMgAfVOh4nYpf15SQ\nzTNV\r\n=oM4o\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIG6d+zJafKsH6nqGGxi9qrZqj/F8I16AI/OKvOL8NXT/AiEA6GJs3fiy1PZn8mX4MFHGSIUpcZYqdtmDpDjtqlyGw7M="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.2.1_1553679612859_0.2038947936450517"},"_hasShrinkwrap":false},"7.2.2":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.2.2","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-testing-library":"^6.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","commander":"^2.19.0","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"gitHead":"874186c464a816fa0d45c268186500eeae0a0afc","readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.2.2","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-b8h5gCHc8hzfC41rx9P/akDNAeo9SnJMxxagi7WKfd97SJtyggvGBA3xYJ41KnnYjGw+bwQDl4fE7yV/VkWacw==","shasum":"53e806a7e0225824271d0bc530d8462e09663364","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.2.2.tgz","fileCount":46,"unpackedSize":226155,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcngq/CRA9TVsSAnZWagAA/b0P/RBfqDDxOpvVGv9xDLb1\nayO1gfPsPQT8TUoOSs+TLHie2GUod61O+g7dZU3iq6iukh5i2d7PDjN1bSCs\nDADQmDjrKYBCeKNXAPqNvi95xC6At9IFcuXL9hZwXJbKybaq/7PVMvO+qRih\nIjBfQA7NLI3yWrR4bmlJLK3dM8guHFToZsfwcCD6QJjOseR4JDWA50OpI58M\nqDZmezxiY3/74VewCbpnKzewwNBkXVhu1ReBnVM3/Bx879piW0J5fdLfE/JR\nO57tbAGlDxxvTDRCc/aLDe+cWcAGqBbAUZEmVx2EBCtHgH0S4WFbJJqvdCNa\n1tjniU4VUcqh+Mk18XluRhA6Qi7dj0lOSY+1O6yxphpktT6i8uR/4IVidFFb\neRAr/pmGN24mujj/VIrEvnpRqXOCLRBWfMQJjBPG2+d9FdTq05GUx7zcDycN\nfufk6bz4CUw5aWFsjRoQN0ugK/x0hHqkzrfjjNaotw/lZ8d/R+b/BUy1ga9j\nKDAg0qVPCGaOnPDnPUbkQmu8ikpNNvYEDsKeFMWtmxO0otDOr4KKBBb0WupS\nt0wq83AhqxhVOtZoNSXSZa1310ey2iYNYQQ/Z8zinoklGCxc46hYgW7tafF0\ny2Z22wEJTIKmIiFj3PCufpOH2jCGuK8q56Nl9by0Qq4FPiR5H4ledyAolm16\n9SjS\r\n=W+Ch\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIAFiBXpTrKQXjc4zdZlJbT9amknr/L90432d/l5IgUAJAiEAmeuNUkSWYoWrpNip/trxM8cw5NkYxF0RVyH1rwo463o="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.2.2_1553861310691_0.8709284964375366"},"_hasShrinkwrap":false},"7.2.3":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.2.3","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-testing-library":"^6.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","commander":"^2.19.0","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"gitHead":"b7918368b47f8ec61c5f44ac02a9dc60e6a0a98d","readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.2.3","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-DD+mFemQtUXEqBG5ttxgsVncKtnBQ0B+EO0ea/yH4dZCpsNNBGO2YRC40XOk8/2rHPJ6kHfYNvPoQR6OaEdYBg==","shasum":"cb7be9175e5f9cd450a2f183c890951dddb244fd","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.2.3.tgz","fileCount":46,"unpackedSize":225881,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcog5UCRA9TVsSAnZWagAAHu0P/12X5fb59WmZD6X8qeBS\nuIgFvkZLQzht/BMBsh5aBKpFumGssbt587i7wCo3A7ISZ0PlTSAjOJSED9jn\nd7DsFMwMWcJCC/U/jdQkjrY4NtT3+wn1POBji7jSg/a3VHUE4mTweWiSbXz3\n7zuT3K572n85estosHgcInpZom/wDaD5t9Ikk8veWhflt0Y6NbM3ThUl9sxo\nyA0JVlv7dlsBBBvTXB4P1MXNemv9TrP4PQ3XFBP5m97NS8WgMZXMFCxNLzjC\na7yHf/MHnqkalLSxjUEemoe5btQ9gSJDTZu75T/qN2wSHzvDTpCAuDOfPTFM\nJ/x9Hv8vBQp+NYApdgSZtlb44/h7r+YVRavo0s7pTelOX6W3PXl/Hf+iSr3x\no1CTYR4obMRDHF618nad/evvQUu+HO8kLVbsUXlY529kdgrmF1/bg22bxVQ4\njXAvDcdPoPO+Mw1TWvhSuPac+xGNCvmxTPE6Tn4gqOWonba4dvuTcaeSjGUY\nXrXkJ+5BEJWpegF0E1JZYRrLNbRboQaK+uJMMU2psepyIyHNhxZCuKfShfMW\nd2b8GGjl+gWcIOQ2wpXHniJAaHBz/HqorBpbfylG9sr6+T/ZBktqWR8KDuAr\npOo8vLyinyYP/+6YnMFTTru2JGy+tOTsE+fbqnqGKMN3wNeWXqpirBkUzZHf\niCa6\r\n=9CUS\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCGnCIzl2uIdzOABGqNvYE+OsfUIiDbMBFoJmCOnLJ7vAIhAIU4ovv/+BCJQQeoNulyug+JNxnAld85bnvAQRD63LP4"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.2.3_1554124372089_0.4838247830402671"},"_hasShrinkwrap":false},"7.2.4":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.2.4","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-testing-library":"^6.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","commander":"^2.19.0","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"gitHead":"3f92fe9852bccd40083d0e91198febefb19d9de0","readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.2.4","_nodeVersion":"10.15.1","_npmVersion":"6.9.0","dist":{"integrity":"sha512-/cgAFcrc1rSPrcEFBT4ZOZ8Vy/+Y0m6P1zM7T1IHu+6b5GA/y/Q4qK7AMFgdX0q3ly/K8XhACL0h+xGybJ+9aw==","shasum":"b3428ffba0f4e32f3f6d8a08bbc18341116b9fa7","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.2.4.tgz","fileCount":46,"unpackedSize":224925,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJctaqmCRA9TVsSAnZWagAA9u4QAIPtyXka19Nve0Nh+55S\nrDw4EU+gOfAGfOxcMShIFlncSivdYSHWYszp6JQeRc9TYkl2bl9i5FCMDnb6\nl5VL8zDELKcWOyjJeoZMbTNnI8GoXiKXhappjsM2p3bAWuMoM197+wHE+Um7\nzJ0SP12UtKl6+B9meM8LaFlQ1XHFeqYXfsQRDHYYWCiz2S6uUdl3mqe7Q7Kc\nr87FyMo9IcKUf2+dM/V82JY7zSv/aCzZxPZ8pxOcQY5Z2okzh10wgCKe2oVT\nXJyMdChyW2ciQA/5wKWg9fwRH4BT76C69C7Xkv8eiArOSd2CS6LdlpCQbmZa\noZowoo0IZk32aMd1PiH6/J4SyrE62nadKdClYa89VGV3o9lWfCDCeTwCYXhg\n29FsW2MANWbMWrTIcVxcUBu2jQHWXrCfDKYmpGYgbvOaakjEtPnPrmywp1rA\n3OvcHrbZRmOJJHaka7MkaXP+UmovEqt0OPIf+ehRWG4H9gB0zNcV/kXyWsC3\nbVZMlK8t4mOegP8px8/He/8jYREZcZogR4id7b+HJbbHJAB0+5zkx0VkGhCj\nqDFeDWxfHEtiNywRohPZD3YVsd3p7/XutOVJCLIn3JoXZbppkRyO8Ep4E2v/\neqe8qbQPz6H55lKRuHTDa+1F+0zsH+HQLb+cngjoUwb1SMgB2Uzz/vOSnY6t\nvATS\r\n=hp3s\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCtfCvVI2QeNgO+wNZVK+X5UJgwpA6Vg4V4YHp/EHXbQAIgIcdZbgzfhGwVzpH1WF0pH41SmjWPY4xG5YQ93ubuHkk="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.2.4_1555409573655_0.9388089924169907"},"_hasShrinkwrap":false},"7.3.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.3.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-testing-library":"^6.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","commander":"^2.19.0","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"gitHead":"5741db3e876ae22eb1bb782ba97d23f8aa751929","readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.3.0","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"},"dist":{"integrity":"sha512-kTLEag0DzTAufoE9pMTxXVQtJeA9fsDSgg8RpcAgdWJsRQtK/sHQNboXn5et9aVMk4c34gliZWHa4oHvATns3Q==","shasum":"3a9f951c4591d47188439976a0b81a15eb8bb520","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.3.0.tgz","fileCount":46,"unpackedSize":227204,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcvuYMCRA9TVsSAnZWagAAjIQQAKRFHdMXcPAoav/XceLW\nm3c7qpgqdgUjiU0FUTK4Moasu05DIeyB+PCsBKqUP//7WE/TBbDLNwhnhp7Z\nQR7/KgKlMuxGO1EZXcH6KBlj/q0etLyQXQxOOn6HmzEPKHj6fcd7QsZPcLtL\nnD+uYFbXhSIoL5nuC/5OzCwDggpezjmfS53IDWc84LzxAL3N1ajzBVjAdNU1\nyuSY5LBiHvMRJJWVub8pcaII+ioFvq7CMA8+xLbKLz0n8MiEn87LBuUjOtGL\niOP9q5Nsn43UbrAn3v6dWl6T/JmJ0uofKzUUqs578VElyKsbnbeYuWdQ0xHr\n+xbysF4tt86ojvX6ytCyW2zBPuEnREWbvf7ZESne37JemuijWiJspbtYY6Cc\nbXTBu1oGE7fsdG8sJvAMD5QQr6RTWEcSkSmUlMAfDMLS1kYT/pW5Ocq9S5Uy\nzQm5U8ExeIuSfaLtDpsoT+LP2vmJm7fmPlezTLrJy7+L6oTtd7Kz8JnY8tOW\nJ4dtjSmYeFj5aQ5u0VCFc4uMMYZv9HxLC97wwGP7q/Ax6qza4RmJtjHryE5c\nQL3W2OOFOuG6Emmzzs4vNPTzs+/5BWIEd/jKsM1JCt6zhc379Syj3kGJ0W8F\nbp76Qx++Rutw+b/aXPYWUoqphmMojth+EftpzVZaPv07CWdvHEEsUN7Qyy+H\nZvF/\r\n=KtDL\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDzYS38ZEmvgCVLTo/5ua1N7LUXox1eo8pXRkBeyjcd8QIgFQLzdOe5O2cCOVZE190HLCEyEqo7VIhilA2JplpO5ig="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.3.0_1556014603834_0.7260972694326739"},"_hasShrinkwrap":false},"7.4.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.4.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-testing-library":"^6.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","commander":"^2.19.0","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"2244421b8c1226c7be2c7e1b2deaca5ff9bbe82b","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.4.0","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"},"dist":{"integrity":"sha512-Y5l1vqaOxt6nec0CkjqFq9fS8RytuDlK603EDOtPZ7GtrGav/laenXLEKAFt8VJGOZfw4ZF4ckEXF8ovLdC+kQ==","shasum":"41ea3a4717f8d2528053b9e11480f83138cb36cc","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.4.0.tgz","fileCount":46,"unpackedSize":227462,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcvxQlCRA9TVsSAnZWagAAYvIP/jA/Wb/Cvr68I66AJPkW\ncgbh2oxshGEn5Qa8u9jiHaP+hi9/nEMkyK1MaMIjaf9mngy22H4hV5kOfUcD\nNmS67h+g978ygP1nQrTFJnYCxYyuoUMNwDx+Gqoc7GbcJpUxC5C2DwX6qS4J\nWeRzgygt7XarHz8amZl53uJgeb13+ypXNWUgWfQnLcr9Bu2xH02oUy1Cl/Nf\nM0e7i7gM+rzvdwikf28nOU2WcgXhSxDZVpqkpD63R0sMYT4ku1ZI4fcjF2YE\nQCyed5hguWRPoGZn7HCSAQjqFZ1rVjOY7KRYptmjlErECi4/Wjite8Yb2Pg/\nI9LrUIznk7jsj6DPcYOnenJk7S3+BJB3SvlLCRJrneN08qZltF/w+0Gqq1NS\nCeNvcsGo8VeqGWfulWaan1/UpSYNHc0bM7vua+jKB8zeSJuQ+iyHRFWOqEJH\npedQIR0sA51icqZjMbN3VbTquB1tH95UQZCKood0pSuyrRbr8TOfBBi/9sWh\nrYq7amDNxFoDDwaOeN+te7Mk86yo2v7v+h0td/VirREX8XMd+jRaA6Rg7aJ5\nuPpLNrcbJHOzW92YPlphHdWZtxIXkAkaPETTOIVj0TgegjQWLhoVhVVdUZk+\nHzpNbQInJRJOXXR8dqN49K1EBlVgrBpFxSHmxwR6ubGVhEf9DDUXDIaXkUB8\n3MB0\r\n=BMHe\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQD2V9qf4/o8z+Xj8viJj98BMm25XspQi+JN3CFqF8j+yAIhAMEJKnJp7GPlAAciWtNUceYJjGDgcdycoEd4E0HvPK3a"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.4.0_1556026404057_0.8339942862640048"},"_hasShrinkwrap":false},"7.5.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.5.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-testing-library":"^6.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","commander":"^2.19.0","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"3d8148462c5868e2af9712dbed5e44f0877905ef","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.5.0","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"},"dist":{"integrity":"sha512-tmrVHieXQih1+Qch9Zkr+SMAfK7qKakwJ+2/WvHDF8NbuxcJ03hlWLmXuNJ1Yg6Vnuk55VO/sWMFeoqNwZnpAw==","shasum":"389f7b47b42848f728d6bebb61cf7e1aca845cd5","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.5.0.tgz","fileCount":46,"unpackedSize":227561,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcvxhuCRA9TVsSAnZWagAAncQP/R7IvUFE/gIVuMdvLDqq\njKC7H8iXFK/DrDe4w1bMRckPtO44myK48hYm7FaLgY/YvmnSBSRQLw76pVrw\n2WRBqC+F6oaoEcsPse7fqOHz23Mji0IGkScn6OtXp2K1IBjrVaNFIM+v+Skt\nsoEU5A4NZc2Qa8VrAuPsmhY8wFyDu6hk9hPnCRskDILBkcp2b811u5Dzj4lr\nSnTHai6KboqpREGt6+HsPy43Layd4v3qzH14DKRSYNEdLGd34GIff7/4ujPq\npSud7jsl3TnDCHDBkEK+9jD2Din2Dp+hqVI/79xAl7EZajgI5my7LBUv63D5\nByetvKp++2EX4hQeNqEU0SMKJFLojkNUYheaDrNoBrvXcuC1oaSK1DiA/T6Q\n5FG3CHaMubk3FoK0jI0tsSnRgH+Ac6Q3NjWRHUslFA5JovpLpravcnXbtWgJ\na9DhybnocEVj53P2M4Hi1ztg7jq07RagdJLT2Qu59yg8kMy6j2JtT6VZ5NDT\nXMAidBZ9ZuTLagYzvnzopL7aBi8EalG8WK7xwiKSVaqqu62/ix25mzO/CDP5\nVemq/TiWx0i2qISyBFbOVs/wXaXsLabbydAlnABV0dHbxFfyeHsmUFzQn1F5\n4KUO1B5l1wlM3XqNgR2OeVdIr7gFmqta9DGv9iyrkSE/OhkBoWlPtg4ng/zh\nOk2i\r\n=050k\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIFkUQ7rl57p4PsnAmR7HQKscnjFRonUtXvS3rmBn6gKFAiEAuVPldufc5uztYTPjlFsCsXrRFb9Af4QGsUhH70rAxZA="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.5.0_1556027501989_0.7276302977827265"},"_hasShrinkwrap":false},"7.3.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.3.1","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-testing-library":"^6.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","commander":"^2.19.0","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"b3a76ff18a07a1b5b771ef6f3fd8ef1768faa66c","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.3.1","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"},"dist":{"integrity":"sha512-7sx6k1RqYcbmZXK+4KK/oSVTdBdXJ1iwh77dqCgjh0eg67qmLGmkBPW9aKIaNrCQiEehr0sLMNwz23ku855vmw==","shasum":"31df3bdac0f6205d480da1523fe9af4594739d1b","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.3.1.tgz","fileCount":46,"unpackedSize":228786,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcvxs7CRA9TVsSAnZWagAAcD8P/jtfGGVTDg0I/gFKilgS\nB1eXZKJjsf8fRkhPWPGT2PgxYl/Zzg+3E7r5Cs1WurAppshdYNe00CzDRoLj\nDm4OvmMESfYkRz3aH/Yfylyf6fFXqn/BsgwZEb9tCe9322VZ2oyoOneDFxOL\nxIbTiDg1oJJe73oprMmm769Qu6g1GbhP5Xx6iEP2gtJgsJ3CniXTXh1+pj61\nIs1XO92R1ljV1oXr7y/h2gyABOKIAO0/r8f6eO/BIayOdWQssvPNvZb+jG0i\nbW5C+HplQXzGs5UeDM4i9/pLV94u1OgLNvIw7uX9JTPgP46dGejhJKJM4/bw\n7EnpxGYsoNF4ZwSRCdIWNK362f5CM6IdBVFhxH4/nnCrQzjFSZGPbgQcXsa+\nxtbIIvVh2/KrYRMi3cRjWgXFl+Le7gB9cmLjZZEgiGcvYAKVjmfA2TKMce6t\n/rhdmnvsLj0UciPoqFNpWev4eqpAGfyAE/AeyjMrCFmiwBo3SKKvxoj17T6A\nhjtvmV1Mdf+OXWNoU4n0TxRfzZGPJTJbjsBx742yrLolSx4ivsobxJe2C0sn\ns7m5Y5MPxEEwxCIOpRv5ZldC/pEa95d04SaYKoi1nt1rB25/PoZ7o2dZ58AJ\nEs0Q5Ym49DD8UAtc1y8GYhy+PiWIVI1AdbA0ZElbMRJueh4Z69Fgic73ygqP\nxepJ\r\n=pZbW\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCgtpz9qTHHccUqCcbaXbTIn19xazwlOX7KhPZzVHKe7wIhALdgJVRAatovcehUc/5yjMeIP5Yu1+Cc1DfML7Nc2BT+"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.3.1_1556028218898_0.5085996218307194"},"_hasShrinkwrap":false},"7.6.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.6.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-testing-library":"^6.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","commander":"^2.19.0","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"b3a76ff18a07a1b5b771ef6f3fd8ef1768faa66c","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.6.0","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"},"dist":{"integrity":"sha512-TAaMPeeVbPu5Xk7qC5/Az6fDf+lAhbK85gZbveWLGs7yu7AWr5bXK8ClsNIZ96iaONZTZPouK++HY2o4H8ficQ==","shasum":"4bc00061f3017fd12e4bab6a7645b972ed5d9194","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.6.0.tgz","fileCount":46,"unpackedSize":228786,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcvyk8CRA9TVsSAnZWagAAMG4P+waxFZnAoqzkMY7AWr6r\n2aiMbZ331hshlxiW+7qgbBYMJ1yXgxrVmbwTLe5SOxRaZabIueuYrHPUxalj\nfqLMDO1BhDIoHxQGydKYVCpZqtUPZOvMn0mm7K0BaoezAIA0dm1a4X97NW1o\nLtepELhNcyw541sryypRUoPrnaTMWgdAuaWsB6nOEBcEum7WNC0xYHb3Gyb7\n4r5qbqPoHFdCEFOFK1THmEunbWlhTgUMFRRwtXXlmbQPWrZSXG4MCaQ8fjQD\nDH9iRKPVDziv09TkV2k4MdSpyePudE1Wgv1UqEN7iwOtJ+9lm6ntBvNojf10\nQwBiWHD25rrk5ftyEb+gTmOnIz5vfS6+VfjZPOOuIF2z4xKHXyE10DarFU7g\n+ZiXxTBmg7revGsVVI8iWwv6F3tJuWvGxCr7kDk8hEuoHoFSWWjwp1DC1chQ\n/l71lfkK6SG7NwSYD+VO645y8K3WlpHFA+gKIK4aLRZ7EHe7x+S0Mq2Bx8L1\n8r3rOqPOoZ9zfdz4d9r0rVtLON4OLpjIOsCS9zZOyHb7UVQ6tdnWgDKBgrQ5\nU8kaQ1cqAsWSWvYoOEtwFghmKsb+HFpeuTgQ9zFV/XVo9SQzcGwUO5cIb2Sv\nk01gEG6O0yUp9h91ImVOh9ifarRRGXXTCOuMjma24e1Y7RuVXeKMSSyALkMB\nOLFw\r\n=fFgb\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDRTyMMZeEbucAyGqb7+uegSbu2jSIJdUJxq9xf2U5TtwIgSPLaKsEz/gVPLMuNl4vWsKQn0pTCDlnMhH9kO+6hA1Y="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.6.0_1556031804140_0.6899090112549877"},"_hasShrinkwrap":false},"7.6.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.6.1","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-testing-library":"^6.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","commander":"^2.19.0","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(delete, {loading: isDeleting}) => (<button\n                      onClick={() => delete(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.6.1","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-SwmTnZ1ZVpWL3l2d5g+xzE6uZHSiMRwnMmJexzkFCIbuw4kr2kqPmXMRw5fJ71uTnabd9RwGQ4w/a9veFlv97A==","shasum":"cb0a620313e9a8a7cb31e6deeed74445b22515a4","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.6.1.tgz","fileCount":46,"unpackedSize":232989,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJc0t/BCRA9TVsSAnZWagAAtKkP/Ah3n7C00JTotYYEKll/\nKcd91LmjpzthtsXVQOH0HR6d95qSzJkj75TDnerJUVrSo+9r/BzaVFq780kF\nE58gZthTxJiuUVIjaTTGbZYHgcTViMOFJAzJ0DFGhRa8GnHoQMLnuLDC7+4m\nUEI6At3uUeTBNPVfOzxJHWRIQNG9h8EUxYx8bki04W1BXhtr5SJJGlo+6rVR\nUIs2+04qaUOkm0XRjSh4zSWXT0qgfFf5jsdyY5/lwO0B9sZu++R0bYOQ/dXW\n5g4xvhsTZaxvn8hT4YUfLHNJCVqwRCXpKLNI6NUuqTsLG8yBbgr42GlP0NPS\nwTlJAumVMP5lwwf084QiXo8zRkHq90dbs4FjXNA9LM9sz7AsooAVD7W7ZIk7\nFOS9kBbPVR2uObaa/g5oKo0D+t8sFaDd6m+J7ylbDqUnGd4+41HbJ3WWCRMb\nzcbAqDpT2Om1RuwxDhQVOcV9En42d6FtgtlUsHwp9F+drwOZBbCCnTQjzbsR\nnC+Qrw2EqV6UFQ88ArursmekRbtoxrPvzvZj5LJtgi+xHPdjK+igvYsxRwjn\nkj5e+u7i6V6zAXgca+yyoGNZbtwu7sly3L8hpcjBf+aVkWiHTdi8WJ88AmbV\n9qdN6E2YzS/TaChe/qrK/C6NmntDDmPU6cbFjSKwRDvmnFeeiIr9Iyw6DP2L\nyvDb\r\n=zmiU\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCpRjRuEIr2nCXFoldwMoU/Vg6457RNqstCvYdb2In9EQIgBgP+Hdgb+gD67QvhYNdKj68iw7lu57CDnPynCjhIyL4="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.6.1_1557323712431_0.557554980360889"},"_hasShrinkwrap":false},"7.6.2":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.6.2","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-testing-library":"^6.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","commander":"^2.19.0","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>{animals.map(animal => <li>{animal}</li>)}</ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && <ul>{unicorns.map((unicorn, index) => <li key={index}>{unicorn}</li>)}</ul>}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, {loading: isDeleting}) => (<button\n                      onClick={() => deleteMovie(movie.id).then(() => dispatch('DELETED'))}\n                      loading={isDeleting}\n                    >\n                      Delete!\n                    </button>)\n              }</Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"728ab8207fe9d2b1cd25d88e2770083d5facfee6","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.6.2","_nodeVersion":"10.15.1","_npmVersion":"6.9.0","dist":{"integrity":"sha512-e8bGXSuDxzF920ZKn/HSs24k425skAQOheWQ/Jd3sgeVS70tGoYC7PyoxlYNPNfAYLpR3zeCOn2mq/f94jsLMg==","shasum":"1c754f94cecdc5494d1bf39b4e64543fab9b7104","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.6.2.tgz","fileCount":46,"unpackedSize":230100,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJc3TDnCRA9TVsSAnZWagAAwYQP/3RatNG+/iQoG5UhDOuB\nctDEkEvfV3fYpWFk4d+YFkkBEQQKdw6zztceHBi4L8zSJGE3WlZn7EwjIly1\nkfSHOVdZe4wb9dLYarUa+lhX6Ssnww6PI+nnx2LCpjH7dtbWIbPA2+4sRW13\njgHYWYU8tZ5MXqljIxYWjcTSzin0tJ4BWzIdZKXOVzqWg6cRcXO6aQSJ4E4B\nbo3nFxHtQ1eItXT+CnHVs7dJ/Zq9R94BJGwkVAVTDn4wThBXX5jONJdShiGK\nPhO8Mzzg0irouYOgYNxYHA3GiGaXsxPWw5B/vKUgtuI9HR4E8DYR8Uu0dXlZ\nxZPhW5AdVmEq17SeuxlmYRANGZVBrYmPiKfHov2eHqMmXY8SOjDBWFi5EuIt\n6hgbll88/jA6OFLljSeshMDJ4LLC8sswAf1z3qxwbhudIGP1OmAdBRMsp2XM\nC1xlchDZwZ88f3538SQWHu0pSygQrUseIjeoyYVC9gzlbIiQdtdUUWvTuiwU\nbFwyFTSLyRtkqULgfEuLFoFH0mvWmxwLkNbjR8j39jKYhuSKVKb+NUdsTKZ2\neI3lUyBg9mbrsw69EhlG/CRE9Ibg+E8ZB6RCRuPtIftwbHHHdl5UYNeCIWvC\nEpmWaFIDvmLlffVCTBQCE0t2TkxQSZKrZPS/3KvIR7DaLrSiL2oLJb/5W8i7\nWaMv\r\n=CeGR\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDo57x8JFgmz+RAEHr2ozaWA6JRTI/S6dhov0t0QLHXBgIhAI9T20o6MIXXHRN4nXTB55iM8XgtVublJtwT4mZvRRmA"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.6.2_1557999846184_0.16393937925021107"},"_hasShrinkwrap":false},"7.6.1-15-ged78ff2":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.6.1-15-ged78ff2","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nIf it's too noisy, you don't have the time or can't control the open-api specification: just add `--no-validation` flag to the command and this validation step will be skipped :wink:\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"ed78ff2f7b8586991e14497fdc5779a59c96e9f1","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.6.1-15-ged78ff2","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-w6TbwsPGKtwP6U+UpGSh6PBS6e8DsaW3Vh2wKl5RPS57VukGT5Yx33tZllUhwBEm9xEHo3GHAQWpShOqdObiTA==","shasum":"e2008cbdb7a87f655b5424388f6e7dcf5a038a97","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.6.1-15-ged78ff2.tgz","fileCount":49,"unpackedSize":257341,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJc3sojCRA9TVsSAnZWagAAadoQAJmu9ykY95MWR+lKqs4j\n7GGKTsytWQCwCps4u2Xb9rFXh2fNLuQdPHzYks5FFVUq4cMDi2/pApkeeAiu\nCGRYrEbxssm1OqtklO7yakqe/6uPvSfsG07SvlM00HEwaufE2N5RNg6pzvnp\nwTiNv92YHfUq7glfZHuMe7LXxV4GysK6Xa0fdk3PRMGMPbG4ZpOBvlmLMakp\n/tm6YJt8bgeqcJ6z0eHHMfU2zOMgxdMVQ3fo8KBS+KvRNHUUhLNCThxjt0mF\n/NMXJuA5+Ab+0p6cF5y63hE2cryopN65osJ6Tld1crMxWOdF/VBNq1tJKoy7\nxZo/qOuzgfyKzfmCht5YCjvaDKBh4PytNwmkVQjp1iOWLlUE5T5ZCtq2C2xV\n7DnKhLW9R7G3KRYNScpQLJIsgkHFXh4GpZDrc6pll8h4GD2+kD8NBH7CuYss\nsaxwWMhkmwQmyxpzVtCcokA75qQeTrfPOBggV04XCImG91FmjgZwTCpIcoTW\nc2odDHKwprI/N928gCl2AUVi5CmsH6JFLIgTSw9Un++tZyG5iNIbcs45okGP\nT7+yeq3kZxpvW9kA3aqoKWsxoEWk/WukgJU5J78h3WRD6GmP14eqmRxDcDkV\nnJGyUXvEzTQ2HMN9HP+YPTTTZoWrmbqHMxbBMaip0PWyFw8zgGLJEmffr9dB\nNyx/\r\n=gAFa\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIHcQrP9jzVOAYY0Yz7Y8LswJqSxYtIcTibNeDALvJeIpAiBrzTAMFT/oUf3pYvOXZC5pqySKgXyZh/W0+xO4C1jTbg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.6.1-15-ged78ff2_1558104610639_0.19535357554439114"},"_hasShrinkwrap":false},"7.6.1-18-gb3cc099":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.6.1-18-gb3cc099","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"gitHead":"b3cc099cc3fc79ff0fedaf6c116487179e6a140d","readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nIf it's too noisy, you don't have the time or can't control the open-api specification: just add `--no-validation` flag to the command and this validation step will be skipped :wink:\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.6.1-18-gb3cc099","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-PqhHXbgZGqyEPjk/zVP8CFmf4KY+Ru+vQ3hGZfJpO68eT901cYfNfRXQkEwHXzHyAGF5jlhhNeAYUvL25A58sw==","shasum":"a51a5c4c6b0c9292352f1c85738acccdd93b37ec","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.6.1-18-gb3cc099.tgz","fileCount":49,"unpackedSize":258141,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJc47YaCRA9TVsSAnZWagAAGEMP/3lGV/PIAMI7tDIv74Lj\nysAb6YQirO+hjwp8YM44FL8SQoK85kc44v6AHhmQv3+StBZb6B6vt6OvTi8V\n09nn8HBQySLlogn4kPAzdE6N6c8Wg/zjfT7faYAkkLawBIeQbdweo5aObfPU\n7fwCdNsJX5HoxXEYA7TXSTHx5QjDwMu6BVOqUtVnuUje538iIRZ56WNOxZKW\n1AYqp0n4d2a7V7PVrMoRX1gO8vpPFtohSsgh+AbBT2ZhXnJfrSPcbRgxGrKE\nLIiANscOCiB384DNEBnZsjrEzrdkdc9og6YBKeS8FPbLbIFZnrxXFJaARNwb\nFYeYUMzFieaME2dFIYs69XzfSjQjUsFfikqTHik0xOMLtct+FgpGWfbF7L4B\nbZQruz2LQ1xgUS8uh+qC1CdMt4xRSKOnv1G3PNCi6fBcTlpXNV1QAOdOrpix\n5tX7ZTZleRdaZ8k18mbsgvM0SM0bjarvdl+j7KyOTnvrU29OCRmTMpAoOpZV\np+qaNIWe8A+cEjQMI2RDVarlER1dtQBb5OIfKMwjknS+aBddEWjPLGKdsJCl\nSgIMtWXStXjJpIuV0EJTfNE5H7sGNPghk6hWyIUj/0t6uEXFgpGUYurfCSHo\n01FjT/ppb0GLigLzpAjxoIUWzTWJ9LD37P+X/wK3aPy5oJosFekSA7Wgiuvq\n8XpM\r\n=hicu\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDSFX2BUkrvAhtEWm3cIc046iC/Jgg5wPYztD7yIyVzmwIhAJZf8uC4zp4pK3H5VI67DT2UZij9B3+CHIWAaE2LFclU"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.6.1-18-gb3cc099_1558427161629_0.2683159662347574"},"_hasShrinkwrap":false},"7.6.1-23-g168e6e2":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.6.1-23-g168e6e2","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nIf it's too noisy, you don't have the time or can't control the open-api specification: just add `--no-validation` flag to the command and this validation step will be skipped :wink:\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.6.1-23-g168e6e2","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-ZwpQP0nJJ3k6oULzri+UdfBQWbbrJwoLMDw0Q8HP2fliVo0wVQN5bujCHAlsAsP11krVce8xxN44tMAltwh+0w==","shasum":"536cd0c8e03bf085fb18188e8321692c35b17516","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.6.1-23-g168e6e2.tgz","fileCount":49,"unpackedSize":259939,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdAQKZCRA9TVsSAnZWagAAaQAP/0HiTpgS9fEE6GPUAT0t\niJHXeiIfZd5g4D2hB4rKnaaySzKAGlhlrtKZ0m58XRAzjKLc5MXOQCCXxKpC\npxJF+82uWIfZvX8ys1+8I0IXc5iCySTpbWKVDgCKy4ihlhWlAusou/aeuY3n\nQZnzNF97J91LksGnPrumv9qdnyXrxj2lTONlcdKxbN/O235HDGKdny42s7LG\nT69qHewnzlVJn7IJKYLtgnfTHPiUJeS424Qz+u4pKvLVmIjOmxbCIrU+eGrk\nGMZjNCZ9y5M48KpztEPiMZFh4Y/zNJP63e6G+V7Qw/XJyAQUt78VrHEKiD1K\nIZOKPEjkCeWdTYhs7l8Ey+dllu1Gse5zI7X6BCBYgQssbMFx8v/X/wOobQVx\nGPBFgZTqfFqnKq/uQ+U35ItPhEWuMCbjMvRB3V5UCDHeKHI0DpGHcR1s2cMM\nlMPoLKfouBPJnK8kivSzNGr4lczWA0lddQvO93dpjKZybc/X0PZglYRGsLnu\nW69ieVMZyrzmazqugcIKZ9YQuNMtnKZNRvV9Zx1SKg372ekRHCRbivWgARC+\njuh7lsFRWEIPRil79YDeOaPOJp33+n7hr05Hx2W3nBSmfpQbnrM6C56xryXg\nQbbu+Gqpv5/4LnnqUs3X0TD43cOYudAz/KEXH1XCYCwgI71wKGCktObZYcb7\nSIFK\r\n=kFFB\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIE7dEeoSdU3Ucnlu8+2KX/72Z73jLuNGQE+RsPAU3TstAiEAvDVg7pQaSD31fsFeCytXnvJLUjgzlf8uP3uFkNHPGrQ="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.6.1-23-g168e6e2_1560347288790_0.32092145072111733"},"_hasShrinkwrap":false},"7.6.1-25-gc689d0e":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.6.1-25-gc689d0e","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nIf it's too noisy, you don't have the time or can't control the open-api specification: just add `--no-validation` flag to the command and this validation step will be skipped :wink:\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.6.1-25-gc689d0e","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-9xNIP7s1fRMS2c4W226/n/5CknIpA35HFcV5qgKDqjBKdKiVOfbr0h+AKaAOyuehzLqrbwv1p4UWUoLsGn91zw==","shasum":"94655bcd75a1a37157b6116310b0fba96f2a6816","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.6.1-25-gc689d0e.tgz","fileCount":49,"unpackedSize":260027,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdARtRCRA9TVsSAnZWagAAUCoP/17263AxuRRPcHpIh86b\nYU0Ffk2eT7cNcyHMtkSwRcxOmUhgA6Z5xkj7dzSnyU1Qz1fSq8xWn1zMEbB0\nPm5i4eO3SdX/CIbPf9NWVP8b66iYJlwInEtJWIKJw6qNG6/omTi84Sa9QJBM\n1wJ3FCUGVxhoDgqi9QehdbEv2rtEiTVRRNgFkGcC6MpTiA23JS+hoBXi7WT1\n7TMUNg/PooZ0Thvat4GzjzZA8FaMgqlt/GNeRnyWJtTbO92GQUrq8LTgeeRL\nsMfmpePsKlGfYEeQ0tLfZcwnEcoAamBIVug4XsIzELuY8rOpqBhVHZT2Xyip\n8lPZbB2ppCjkE96CcO8rOXWgVXkryzVi9KLldHdpjUMa8uYtT1qLHZK6+zcR\nUJKEu6i3ukRgCDz2ss/Ct6jmNDXBZdWwWWdl38g9HVTiGwzqdblhJcnqPK87\nHbhyTxTcjpWp0cUd9R1yzCk8KrzxGgZJzEbDlsUIy7sr0NCUGJJUJBlTKyCs\nrn5Qh4NNOdm9wWUFUc/3InoXsGmvIEM8fgonsvlTWJtGrIo0VIjUg5b7mL7l\nmIMeuoB4ltKlnXkIGftnKzhsMhJ6WJz3Tn6PP0rgpgCYnyjhtD1VDkfpuLfr\nBFHTW4Ne5AZYhD0MYewL66WIgn7RLNuqz5Zkm5cXiTFDr0IulD1nYg0BUM6l\nPW+C\r\n=mFyg\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDwgc1jfIFouY/LmoNaEaWm5hB63QPun8w2rqVLbj92gAIgUMoVOkvguP5415GPkCIZSP+43iU0+Qg9K/4wk5IBMT4="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.6.1-25-gc689d0e_1560353616837_0.9159724697083491"},"_hasShrinkwrap":false},"7.6.3":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.6.3","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"gitHead":"881bea7ae98f6bc79056210612474d5229e7a96f","readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nIf it's too noisy, you don't have the time or can't control the open-api specification: just add `--no-validation` flag to the command and this validation step will be skipped :wink:\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.6.3","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-FJ+qgAj2/6jotExfTKzBPdnxud9qIzRkN4KqEYz0pTNFEESwlsvImL3bGb8rpfNWf+MygjCESTH8V9MvOOAqhA==","shasum":"6ed4102272bbf1873dc7ef316dc6b8b0af101ff0","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.6.3.tgz","fileCount":49,"unpackedSize":261299,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdDNn8CRA9TVsSAnZWagAA9XQP/jDvZ+25vbah1jOlHnIT\nf7gD5fS+qd7m7NRUJZiGuUMOZ04fxNkQeEYeKStF6eVCqpTBY+mJTcucrliK\n7BB2H1qKz7gsTEYgTDKDlF4x7UK/trxsFBVzcTRYiqyJcurhDBrEzodPLqkH\nSdnsv8YSw7Z6zDGMLjIKm+YDF3m9N4f/MBGiL6nAVsGXSxuVFFEkyDimAI7Z\n/dgZHct/I1R0aaEAhQDSov+NpT2aBIcVu+mLYzZ+F4iakSvfQKjJB95Jzjah\n76FTSdNcGrGgz/KnlUeoqb+wwlJCiEOn7CM9b+EEdymLZDOlsOWFZx3pUjCy\nAhvdxVDmCfI88pg3BKoVpeHo05crnWA5yyjw1GvPuBW3WOilzHY7ai0HwCxa\n5zHxDVYaBYvPEzuCtlR5ffikkGr21O0B2EnrHFpbRUiymV0Y84O00UyRPbQl\nFToNoIqZfdnkuOjkACeO7byMtZ9WDmCWsEokCckZbB0LLFUGZRY9/QExoaKy\nTII+gfOZ6YRzseW64CgvzJ2rJ3AbCJkL7W2+7f0nsOJ+bszJ3f/Ptt+otWWJ\nbbaAXMG53zKjS2GFUt3W4a6uFSmv02vZZgg2M8OnQQeFplgyY1HOWvYHhi+f\nOXqOICA+dlN996mAtmvT3Vg94ANr4MTdU2avjbDwLiKSsd9sNefMiSZ8FXBz\nP4q6\r\n=frHd\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIFpz7+TXDzHmmlqpI9lPRf9eOW+4ghoFVD6e+ly87AZVAiEAh+JwpslHaERz49ZO5wcU5gv87qpDB3Mbcyg8OJtN/+0="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.6.3_1561123323676_0.58767396088156"},"_hasShrinkwrap":false},"7.6.4":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"7.6.4","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"gitHead":"6d7216a4b1344bc9700b91bf50138f59166bd62f","readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nIf it's too noisy, you don't have the time or can't control the open-api specification: just add `--no-validation` flag to the command and this validation step will be skipped :wink:\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@7.6.4","_nodeVersion":"10.15.2","_npmVersion":"6.9.0","dist":{"integrity":"sha512-5emo3B6Xx6bmr+n/1YKjJLzghGWbi/uE6JUXZPiK5cJ/rwrBJJ9duowD0bc+6z/+QIGW56WPWtWZUbhT7MmPhQ==","shasum":"ebb95fa932db7696e4e4884169fcab91ebc375bb","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-7.6.4.tgz","fileCount":49,"unpackedSize":260719,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdHL1ACRA9TVsSAnZWagAAHgEP+gKgw8vazCKqXmAL4qjL\nFf7VkTko7UoW8zj/dQK3SMOcCGz7ydkkJkOSPLW1x2JmqmF/jweFIdcT5/7d\nAZZ3CiBOiMMQ8fKASQesxCzvDVHIVHQMoKKuiHWO5aYu45T8irWwrrYkQ42V\nhLc95UOvPXDCkFc9NXWES+auwr3r4VA5mgt82tHUYl0Tm7pa+AhjHDOx+eOO\nVXQ2AUgxKAPdm9h1W7HRjkpEYds9KMXyDyLSW4gqBksr/aziQ54VQE7U5WjB\nCEKoSCR55s03c07qxKvEqvxkwKRRw+Fm8cJn9HD2oEZtEj7umaHhT7CDicXR\nynpWS7MpIwGDf6dcuoweJsuJi820rcF87Fd8G5JYYSYlN7A7NWFm8x0qj6NZ\nzq+tcxrzZW5N877bW1IrGgoHSQBto2YV170MK48oEoAAkAkWjw4Bzy44GG9n\nXeGf+vizIq2+gXcXkCRJRuGj2P4q7bX2uiDsgOR1AQwOKIHbuyD8Yd1HAe6g\nx2V+1dtvjWS6NZLlOK/MKcAYZGZNsPgoLqjjIPZAOVoxZL8fbGnRpZ68AROc\naz3R7PsIf/FzDQojd8QbTluL26iMbgvKXO1uex4DDF2K22SA74xBGQbis6xi\n05zMZJHSYf/vMrJmMx9eWz8+h3JreJM4ru46pUFFAVK9dxUXqOxIWTCn+qxQ\nVRE2\r\n=/nxj\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICOWIqi8rTfLxHjK4hOMO4En1d1r4XGG6Ert7MUxhEBxAiAo93PN0AiLTHwkWB4B+hYKLknTA3FV8hOMr92lwfVCYg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_7.6.4_1562164543548_0.8603312853549172"},"_hasShrinkwrap":false},"8.0.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"8.0.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nIf it's too noisy, you don't have the time or can't control the open-api specification: just add `--no-validation` flag to the command and this validation step will be skipped :wink:\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"529bdb35c9c6baec36cd34ccd76510726b142332","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@8.0.0","_nodeVersion":"10.15.2","_npmVersion":"6.9.0","dist":{"integrity":"sha512-p8pXAquJb3nCQWrNRuXLccQ4g+6mTG/Jzdq3PwevusJ9HUDsPOYri+e0aFD2jhJdvTiirf6Ojm1EfKEou93Pbw==","shasum":"649930accf4628fc3092a7f0c5a5948edf23f024","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-8.0.0.tgz","fileCount":49,"unpackedSize":260707,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdH0AOCRA9TVsSAnZWagAAt8wP/0x3ufji8unTX8ZJQNjz\nUaJKhoxBXDsI0q2yXSyBg51zuxFvpcC0216eU2Irm+mM26BYCQT4xaVo4ShW\nO6CnlI6/8bbubsoxDoXyaPPe02DjzB1uVRm81bFBbXhe4UO4lChV1iuv0tWh\nmlWvth42zWNnLnFskwg2J4G1e4PCbAftGk2fHbex6CEnd8ijZTC5FUGzFGvl\nbhekCjUusb5eown3CF6VlJ7ItocK5Ngfd6SlXboTR98Dx0P9MTCNo+dVsCzX\nyDLk3fWZiXPLzydrVl7gb+DLdfflT5Ax85UdqJvCjFA72KktwY9XjDQ2CBIj\nLF5dge3wKQZSHCRLDTFbUpJjaJgHTorXBSAnQk0cohyB1cMToZGJWWjM/7qR\nPPWACT1quG6hH6eCOSagC68QAtbMte3HvRXPHsi1Ce+O5O5W6gUdnHyocfLg\nXhAeplmsgOHIXd+tUboF1Dgt8NRfLSaldc+qiiHeXn6D6qfRFUGxgXb5L3p0\nX3o/x/D16ctxvKcVyFd04s/K+Kpe//Tt7R7LyixDwDXsg2QY0iJxA85FATTc\n3Vuu8UHO/i7USxkRvaNGmeUK92HW2hssBFAW55Csn2jzqW4G39XaUskqYu25\nQ6NT9yKJhfSeg7/yc4KDla4EoAHCS91V8fZUS3UEj8mrpi0jGwJhlhJ9TR1Z\nEMKX\r\n=8dO6\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDWoUIXee8pAE3Hir9ko3iLOyU9l56UGKg4c4tRsmC4YgIgTzVQE7IZkB8Kdvkh1xJzoNC/6wSVsXxeHFgnydCXCp4="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_8.0.0_1562329100925_0.7283113482438077"},"_hasShrinkwrap":false},"8.1.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"8.1.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nIf it's too noisy, you don't have the time or can't control the open-api specification: just add `--no-validation` flag to the command and this validation step will be skipped :wink:\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@8.1.0","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-nwQHn50OBaP+BN6v/vKHzBdX8WLULYd9HA9ndgKlLQcGe4Yys4IWmJRaZJqmfNxaBcT6BRh6I7hyK+eER0dOVw==","shasum":"472f48f4ebad47e83e5738f57fc9198390ca60c0","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-8.1.0.tgz","fileCount":49,"unpackedSize":266662,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdPwwnCRA9TVsSAnZWagAAfHwP/192UbhXwyannfQn0K3Z\nD0yDngrXJug3SR8E2OHRyf5CpQHfhWWPGuyXW1cZsc8sMqlqCl/Dv35WqnvP\nNBFq5Ttxwq2GGiYaZxPlDwLqyEoV53MYJ38zZ9aTJG414emrTG9NFfsYbZUv\naHTXc5bQFvdtE8bxYvNBFe2Jq71Xt/Oa6ON4wAYq97BFluEF08X+0IVA79BL\nZ5W9kcGo9yyLNN4ZF+60AIIBjHh+2MGp1WMQqdtyNmP5k/Tc5UGpg+Zvt+3p\nd2O/z3+ATkOORmsjxTIkOJbSO2Z0BwR8Kt6JUU62Ts4ZYc++dS6pGGAqEMfV\nh1Ihv+drJb6we0Mhe6JdWpKF4YOJ1djBcRe9rx1wCipupu31FJPB4W7/Klek\nFB3BihOBJj1fFGwC1vCJ44gbF5R5CIyPFpFs34JmS0QzBf+/nyd6lwP0z/Dh\nQu0V8BXA0udVTndkuXyrjnw4aym0PuqI9e7ymH4nITD6JtUqJUJhdaceiY0e\nwq5NNUPQ/lN2TBxjWcNN2PQ9rt5BRkU5cX7OhXAFiBLuR/cNqwd9uwQyWJcj\nOrHT+zIPaev5NFmH7l2gKSBD2D8XWHEytEL49mNMviaPD1LkMIBrzM7S+/vz\nTfNRyZQSM9qs1/Cf8RsIn8arBBWB9M4B+nrvDPKCSChu6F5tojcurKZLKx0B\nt1Yw\r\n=lzVG\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQD5EjRfKJeAFQBCfUbNjB0oqoJIgfZaGrkm4eVf74DESAIhAND/rpjqUYOheJEAQUHhAvxrR9B3le6/hbX9IjowZ8Lz"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_8.1.0_1564412967210_0.8946932418366764"},"_hasShrinkwrap":false},"8.1.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"8.1.1","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nIf it's too noisy, you don't have the time or can't control the open-api specification: just add `--no-validation` flag to the command and this validation step will be skipped :wink:\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@8.1.1","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-OISylb1S3cPBMWfRtrJt8zfvGUg9m9Iaki8i2qxhK3EsoMytD3f3UiNfbwse8uT7Duddmbn4Dvo2JyzhbPguHg==","shasum":"144fdcc0249aad7c55afe03994392ff2fd6a5ff3","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-8.1.1.tgz","fileCount":49,"unpackedSize":266952,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdQAcvCRA9TVsSAnZWagAAskAP/R8Zrhdh7eGLbJx45sqJ\nFo/FKGJnG+w8m5cYBxD5O1cwcNRhn/x5YPS5h3zmjFS5aJl0IRzQndfQpEA/\nb6zgvI4HzdtaEGiIqr7dbZ019vKlOxnpQYs1T0ZGy7Fqa2Ls7O66buBUzgar\n9a9QCjJYECBKvCAQmrf509LJtPQhBdTkZHGQpScCIREXp1RyxpdrqcYXBPZT\nApeAoOaPLttm8aRIJ/dcGoRAV175Zg8c5AKizmvqX62XV5JF7+pP06nUPmDQ\nJH3G7D6K7YCfe1PQAsxLVE3CNaXZTt99I0y0Vp2avKaIrN5cTUM5fhqeYpEw\n5okZBD4LS05VUHAD1R+39T0lO4VTtz6Hd4AYJ/VuAYsgUPtUa08Nw0YYnQvG\nzcIphS0OjKA/W6kK/Hx624Ck1WfjGzegYP7lYjHGCGZy/t+vi4sQxdqV6Eyk\nDfpPeJE2NM6k9A9ttnSqObE+3Kq/J4YpCgP8ZEZQqX/PpoxT3XDjdeQ17O+j\nbttDVgYhGF9mG25qFvI24cjXBkRMvnA2/gFCFU3G/edQrPbFyy/H8hfCiZ5j\ng9LOzysqTaOijbpS9S5urXwnevLFRTFjHQczg98qWPdexzSzmDIMNrPCeZvC\noYAs+WbtEehe3aIxWAboA9C+ROqoxWJpiVBxo34LMcOtTJ7xOXp3CBLl2SiL\nPsXZ\r\n=kdjN\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQD8+vrp+HB/UVg9z+L3aNlAtmNmxhOfG71ZWGFeeKQZ0gIgUqFmSfFpfoc5w/8fwk/GUp9eAzdT4/8IImL8274fbz4="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_8.1.1_1564477231173_0.26857468910059823"},"_hasShrinkwrap":false},"8.1.2":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"8.1.2","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nIf it's too noisy, you don't have the time or can't control the open-api specification: just add `--no-validation` flag to the command and this validation step will be skipped :wink:\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@8.1.2","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-ppCjOTOWWnAAv/tGVEdv3U/onOByH0qXwob6m0a/6ioJQE06grrYhI0xzXlp8h2N3m+dJi0xdzVE6Kt0q+y7cw==","shasum":"c4742c42264e204c0b9afbbcf32a026b930c22ee","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-8.1.2.tgz","fileCount":49,"unpackedSize":267393,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdQBFsCRA9TVsSAnZWagAAutoQAIWtj+2WGhKHBIOlGNYt\n3UkwSA5epixMBHl4IRCJM5GMPCxQZ5p1ZYG+nc/OkidpxhoiJXQJ09agDQLG\ntI0SUN60DkEta64MhsuqtAo4oig+xTExKY9JKENegKYTRJN24PKMOE9zWRAo\nOxCk7g03Yc7WBI7mXEJokpS1gPepKCHcdAyQjm1Grwy0v2GTtpCqyi9OWctE\nXZmZ7J4CbSCMSUp0wYGvYvpmWISwC3fawkBQ4InUxj/If4Hm0LHn+RuEMNIz\nyFVOsttGCEY459oO9S6zZaKcrEbsgbvNmv8xycI5axgBCr1lzOBK1/pZOQx8\nnJF256uSAjPzN+VbVfYvcs3GUVsRpWm95B65C8KbIVyeasqcPlEV7bwSEm7v\nc7jfmqpLteX7xRng1rXN085ElcpPgzJCEiz9a7+0ctjcHRde1Kbkc5dDrrvQ\nn0d4Ha4snl+r8Ox0G/JdZ30PZrVivAxcuPLPnHQGL8xwL9UCmPNPYSV6XqSp\nGF9NodCPLyGb+l7oUTomwekntL+nopuD63xy3tRoD9gkEuejuFBNtN3Wrh0V\nxr26fEaxd25KgFXi6bxzU6OMT2hf30ZPWvJg9a3WJ/0SZS5HAVRjsnb3orVe\njTOTq3+TyNlr8NzNGZPmdQBDr9UQwRiyxmzzFbsljSlW7LhBIxKHq8bfQKpZ\n1xNV\r\n=AGJl\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCA20qEQKDqrqttT+piFve7UGc5IGCh4LVNV0dQhuCskwIgP33iwSF1W/jt2hB4apLrzf1DBQ8YbcJ04BMbFhZNbT0="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_8.1.2_1564479850940_0.3279455410840706"},"_hasShrinkwrap":false},"8.1.3":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"8.1.3","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","request":"^2.88.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nIf it's too noisy, you don't have the time or can't control the open-api specification: just add `--no-validation` flag to the command and this validation step will be skipped :wink:\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@8.1.3","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-kWxkxLlD9evTbUsYOftaElFSeC3O+1/4G4PzXpui8+Mw4pHfs5+wvq2jj2PqiwdwXnslLtwOodkFjRTePu0iPw==","shasum":"8a0af1bece23e8935549ba8885d98896cb4d7026","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-8.1.3.tgz","fileCount":49,"unpackedSize":268017,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdQcFTCRA9TVsSAnZWagAA5nIP/19CEa55WByB9oPpID+L\n4tHAvBppcoBCS4k8O339jzBPMah7Wbs8WBdzhaII5OQD/nMWhGqRaBVSOtfV\neRjMLv3GjzhY8M76eNhb4HMulLGycKg7YjA3hf/brDJJjMuBG3auUoYrUfzI\n+Qn7nt5cisNAd/j9AztkQ5JjoIMTu3IovUeIeW/do5uulx6xFQ+zq4n2x3CY\nzbeOJ9zlbbjfmv0XCOUWrDlz2cnLyJ37BvdRYFtNTlVyA95xQV44+znd9Lf3\nb5BYec7d+fnHmqQ5CzNJfsKbEbKMEYoWP/3ppvK3U7Zxb3apDQ++pq0N0SHd\nvaYQf8JoH8IDQhq+myA1Zk7ETuulVCL+3LkofMhXQOuTlZdYRkQN3kxGWj64\n9C+CQhsthcwwwe6o/08+mruqsCuAVwzQgeyehpJouW2IZRA0cEjQVk+NdNSt\nwLmRuWlFWR9w7biN12BfR9a/ZGlvoyV8buLdvvRWdbj0a2utGOmwfog1E+og\n83rSbzQlNgD4UqZ89xf+kRbWbe4uKwpzdVIupgUF0wya59IWuHPbbVR4baKo\nZ1RnxWQ72wO8XFp9KrLXY49cJv8PBNYp4h9M8L8yU8mgSQx32lq5q9aifEJ2\nt3qI6NqdcTtSZ7fuS+AQmABraYuryHFjB01cWxjUCH2LhoajGZxGUEf5gzZc\n0NSa\r\n=xmH9\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDFAVwm+T6KdH9T8VeWJAmWwpYdVfO8qQgyDnfxZoGW/AIgabrnCiasfPcJd7bx4R6RoMIRkEQE2RbgkfzZvwf679k="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_8.1.3_1564590419092_0.28126899447569786"},"_hasShrinkwrap":false},"8.1.4":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"8.1.4","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\""},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nIf it's too noisy, you don't have the time or can't control the open-api specification: just add `--no-validation` flag to the command and this validation step will be skipped :wink:\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@8.1.4","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-Bm4FHgmrSrvI3gUhLOTenHJJAKhwwACZRlibTW27Zsvg4g7NWqmqxZ4sxDPkPry/ixThhVORsJX4/FV3NyxSDg==","shasum":"fc38ff611fbaef7c4977684a26a9fe478b546463","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-8.1.4.tgz","fileCount":49,"unpackedSize":268257,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdd411CRA9TVsSAnZWagAA75EP/Rx/i/qILbTB6r8Q+VAl\nRaecPjCBsIGxZWBwAF7CRHspP15ZfbO94YvpyDvrJAj92CKM5fZkTT+QY9F5\nAvuSsex0V3o/GEeMY+MTh1gwjNZHU7x+DZccy3FRgl4hw5FMB4u7uq1HkhmP\n8XgPkXhB8AbmT7FeYJ5wb6QeBSXY562aU6V0oFdJbk949D/LuZJ/tPIiVnhV\n9d2xpaA6+JNsS5cZ0bF1n9iK5TGcy8kAp93BmQDL+vUS+KRCBBMWyCu/qUu5\n7E+mgLxZ/4ACPZLxTqKgtxumkTbgoRUhAhxeJdIuokuJESCo71yf2gLYtQ5H\nMWFo9COpxKXnmkHLG2nGa7X+/NShHj/ZPj2ZNdhTslR5x+d9nAz/54iuFDfe\n3Vq0OA5rZEvKXD1h8B4GX5TXlrG6qCwfAfUtRWdYZqKKQv7dZWoOzdX6FP3Q\nY8ZKv8kalgGug9BEF/12ZxxBhWhqJ5C8IcizXJBpRIs1sCvY9m8WSSah0rkE\neVsX6efqIA6LjvXd/JeMNBwIyEA35qpVToloX2+iIvnooBfmLjGagg1tOVKN\nNV5EBAqCgdqZJ2pV6HZ1q1APiE7f/9FeXPwdawGtBddoGTYSucPbqy/RrBIK\nXvk2ZXdoTuK2cohD1vKfy7HX9XXWF3FboZsypFDWuk+R02wHh9tvBv4WiOw/\nS+yu\r\n=sHml\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIBAyTx1pCNw/CyIn435856f2oDH/j88gvBJB0KlvMdxcAiBm+Bw0EZEyoFx80vgAh1hMxN8RzhbChxzgnRdBZYCFQw=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_8.1.4_1568116085351_0.8486219079984658"},"_hasShrinkwrap":false},"9.0.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.0.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, just add `--validation` flag.\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\nDo you have multiple backends? Do you need more control on the generated code? We have the solution!\n\n-> The `restful-react.config.js` (Note, all other flags will be ignored).\n\nTo activate this \"advanced mode\", just replace all flags with `--config restful-react.config.js` (or any filename that you want)\n\nFormat of the config:\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n  };\n}\n```\n\nExample:\n\n```js\n// restful-react.config.js\n\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.0.0","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-DUFW+X9Kz6+XBTPf2wnV+K35JSzsdKq1kiSDlnVu/LVdJe6aAAXYX8MOKM5IlJRISJtbSEFDNrdCtZ6VqRObTw==","shasum":"8d22033e99cc012984cd5cdc736b722a23975d2d","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.0.0.tgz","fileCount":49,"unpackedSize":277249,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJde62DCRA9TVsSAnZWagAA0zYP/iRBtROiL4zOO/oRCvQj\nkHKMVXMuW136lceJuHH1NMVZcW2HHB7F/ivfp1vKgm+VMNgL4+K3L4mXow5L\nNo6jnNM/EPfonfpjoU8tS2KbVK2S4FZ36JyUs7vxjfIUj62cvF9FLl25yULJ\nErpGjFIB8R5Q4yykZAKB3mNHEYJXJxrNc5wmgc00OEj+VMc+T8BcbebSiKTd\nYygILPmYOIKZ+QyYTdEUImT9gEyHa936uxejXLGmtCMWXzr3nCTVCmCdUpcw\npUvLUhqi4nGEHPQ/xXbiXgnIeelQOgfZVk4oW0hR1AVrQ4bzXkD7eSNL+tE7\n4ckSpASD/4bykZvGd2CqeZvILlNtRB+Wn+PMfbLdjf6Z+oxrXHOFZdfRy2LK\n4jP/WzervfFqxj9tLF62awBXv0s0r4HgQe9P3+w3zLU1pKzvbBMV1s4MndMF\nZ4AqOF2Ool7SMLGO6UTuBJPGt1ZbVH02r+NbF/u5CCuYuuAnBjv+rFs64E/M\ncNYc36iJRgP+zzdb5DXsQuueIWdMJjncegEzPi+bFDecpv0tL2fzpc6EgO0O\nRQCQ5c5HCCf793ZYrz7ZU5YA3fXRJ6xcn7rKIn+OhUQSl1P5sMPH5wzPY6MZ\nSpOxR9GBOltR2A7PUjk+oFcqUa+8EkgUoTfvUGnK4rgup4kR/fwOL+AP0IVD\n1ce3\r\n=EURL\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIDZ4dOjG7EjOnwoPZXvOtytD6y6cHK8rrbKL8AEiW/KmAiEAyFo/+DWalQMHDgIwDaD0+cjo5WraUyx3MbpoSiA1A/k="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.0.0_1568386434250_0.21735171156380884"},"_hasShrinkwrap":false},"9.0.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.0.1","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, just add `--validation` flag.\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\nDo you have multiple backends? Do you need more control on the generated code? We have the solution!\n\n-> The `restful-react.config.js` (Note, all other flags will be ignored).\n\nTo activate this \"advanced mode\", just replace all flags with `--config restful-react.config.js` (or any filename that you want)\n\nFormat of the config:\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n  };\n}\n```\n\nExample:\n\n```js\n// restful-react.config.js\n\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.0.1","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-oMagT5Hb2aqOdjeWf8TjZBJ4YD/8ZnsO55H0GjkSR7fIeeCLmy7Ue6dYz5Qrkl9MZiSs6jDSw6czAqvbJCDhmw==","shasum":"d43e3a0bdb8c135b324f506d21f19944df6f3329","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.0.1.tgz","fileCount":49,"unpackedSize":277289,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdgjxqCRA9TVsSAnZWagAAxgoP/ir6jfeWBX+53euaVn+0\n8Fk/5Zy9G4BOLy/xFunQsHJajrtNvvMO8/uY7u17Rw8H8Q+VAsE1X+5LNDFy\nsGMnh20mG48vW58qbv4lbuNcrb7SXHLqcCQebTa+ibkJkmdssRtE6Tw89wUU\nw77vmNXy+U8LuyePjz4tj3zVXtQ5jKLh8LCsBUzNvgv/fI4GQnXgeAXo1uqU\n+2hmrihmoS9s0uxz6j1iEzuhpPIQVvdJ4NJ01jX+vYOIfcOAmAqIPOMlbJqh\nqIuBUwR/1PDJG0/zjKSv34vasgS5V/2Rsmz8e8/suetnwPJdu3vOAiEHPhaz\nPWlAU7+NdAFWDxnjZzg+fScAOCJpJEzklNQ/EtO15gEj8LuPHOK8j/FYZhRV\nxvOKGVvwHTMkG5fYYGKDsRzru/ENYP06VW0nrcsY66P/tc4iV2XgcwxFwB8t\ngJSJYlj/Qi8o72/gvYa4mL2CvkLCmjwVipn4HoNGt+DBeq/LNMbd479QK1GG\nm+TbWNcSZgah52ZTG86GuYg2SOatEDk8yUrk1Nqqg8D5kUhd2Xlky32c0YZD\nzjj5vxBDg9S5q738nipKHMOw4UMWHApdRGtTa3R2gaIHe3nUJKuX9s9Lj+O1\nyDZT/1N9aPubDvzeVQK5c6Gpwd3nSndAYHLzIOVdiGiPnrureoTJnKxTENhL\nnfPG\r\n=1Odj\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQC9EKjteaWRD3NsXhQInwbTMpref6xyyC19+dfvC2oz9QIgB6p09kz3sByMhl3eOz3gn1FMZgAkKk9ySNLaIImP+To="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.0.1_1568816234226_0.7803403325890421"},"_hasShrinkwrap":false},"9.0.1-cache.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.0.1-cache.1","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000","tiny-lru":"^6.0.1"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, just add `--validation` flag.\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\nDo you have multiple backends? Do you need more control on the generated code? We have the solution!\n\n-> The `restful-react.config.js` (Note, all other flags will be ignored).\n\nTo activate this \"advanced mode\", just replace all flags with `--config restful-react.config.js` (or any filename that you want)\n\nFormat of the config:\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n  };\n}\n```\n\nExample:\n\n```js\n// restful-react.config.js\n\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"e193b57ae0a7b372b09a017cf96feb8aab556d18","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.0.1-cache.1","_npmVersion":"6.4.1","_nodeVersion":"10.15.0","_npmUser":{"name":"stereobooster","email":"stereobooster@gmail.com"},"dist":{"integrity":"sha512-+7AtB41k7l6VSPKL35lsFf9OoydHr1zdqXVc9Hs9rtaTVLaAG09h12NvbCk5hYrZX0RH5AQhuCGKTOHDV7f5Wg==","shasum":"08ff38c7022ef8cf9ea623e52b8902e3cf671b61","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.0.1-cache.1.tgz","fileCount":49,"unpackedSize":276163,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdg2kaCRA9TVsSAnZWagAAAYoP/jYBnr2Ytin9LxHJFmtq\n00BpEpxslxdQRF98l0eXUCr0dtTKShqnEtCsVCek6vkrZHXbStesrAvAelXH\nNHRZwarMH6uVB0lm+qfDfqYv3YYpTlQ1Fqb48fuo1JabTbasiGNlW9vvAO1y\nm4P7Pa9UjAFz0bx8FOkpmsRk298qzNmuFWjEzeBWtzR7tUNY2JEhSKVgPcss\nPBCBQ620xEfAaYoaE3xO2/LLlc6n+nnL+oD5//aliIvIcy1Bnohh+gosXp5H\nrc2d3vcSasp0MWemQJocnRTeFrQgY7pDRezTdolsFxHPK2+5i1fQ+fihyptz\nnyHpTAcm3Ccx0W8KLwJ99Q5l9DyFbXMLkQrb8Rp2MtyxDwNWdIeKVIXuNKS5\n+HMWpGmA342153ZfvRcd49YYxZqJbNg8A9Z/qV38ExvY50iIjtyeA7rZIJz/\nvrnVg2bFyZOHawM0VEsOkEu25IuqNXwSFxO/BbAM3HWhju5mHculEEU4Yzqc\n9k3TyiyPA/c0KkYTyamaKQBJKzRlHbeDBcm80lWjniTY/HFmqsshUMc5TWAY\nBRm8hVJAhsDm+tgb/lQZZg+c4R5RmGY3VcadCaVCArz3xTXyWWCj+ueHqz37\nKec7nzdIdONpgFg4GmuP0RfkWu1rDZX4XeksrDOMIRSJ7yB/fmHRyKVj13yS\ndziw\r\n=MipU\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQD7uWieeHkunA9fpe6KmMfQeKNejv1hoF6PXTN+Kx0e7gIhALYzQ2zS3W2e9QA10nYwJo3/L7FiVfe3SCzRjaiAF4UL"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.0.1-cache.1_1568893209625_0.402132470798924"},"_hasShrinkwrap":false},"9.0.1-cache.2":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.0.1-cache.2","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000","tiny-lru":"^6.0.1"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, just add `--validation` flag.\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\nDo you have multiple backends? Do you need more control on the generated code? We have the solution!\n\n-> The `restful-react.config.js` (Note, all other flags will be ignored).\n\nTo activate this \"advanced mode\", just replace all flags with `--config restful-react.config.js` (or any filename that you want)\n\nFormat of the config:\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n  };\n}\n```\n\nExample:\n\n```js\n// restful-react.config.js\n\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"6ccc1420210baa0e4ce923c3b6f000661b2bc418","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.0.1-cache.2","_npmVersion":"6.4.1","_nodeVersion":"10.15.0","_npmUser":{"name":"stereobooster","email":"stereobooster@gmail.com"},"dist":{"integrity":"sha512-9drLqObCWZOQSAHwmp40QqGFQBR1ZV9ijABnch36MP3heboF9sq67bO6mLUUcHt3fU8jYba03a860YzsHgicpA==","shasum":"4fd9405ca93e5ad5474374cfe2b6d87757f0f1c3","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.0.1-cache.2.tgz","fileCount":49,"unpackedSize":276492,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdg2w6CRA9TVsSAnZWagAACEAQAKQ1VU5J1hmQea3rDjZa\nSJmxYKMxy9Snao6mnkAlbEdrlUe9CT3AZtX+jW9muF7hXZOny2qxHzFOFqjf\nQblJLDd2mjdzyFZJGetKVYYUoAFFavzRDCinsx10mBrYP5DPt8OOXFp2wiQD\nqTYDJMAeBQiXo9o4E8lehQuQ31+l+NvSfrR1XaxS75azyUrSjAE34x+hpL+9\nfc971bFG3cC1uA1HipsFDALAKUOxGO2QL2CI2hqS6/3JgEQWdIBLJ0d1dih6\nUa2KLGmrbSZRjwZUuVnFqTYe38Zk1v4WfLnfm4BTBatMSV36mJeO5G93SOqz\n14tWJ+i9hup+TCqahYkkjei/VNJGTLsij+9PvVfBnNY5ONSFrh+PpHLLkQQq\n8ypgmP8VMQlyifiTqWr/3rwS3fVN10COPsjTIRYdeAEHlSczX2PjFxT6kFf6\n0r7Zlwnwsq3rQ2z842sMvMYlOX//P70dPURbB7cyxOfaiFugbM2Lny1Z5E36\n0DslA+xtjR8o9MOXOZWU5H1fpwaEJUKOFKtymEJCdZTUpURlzWp95GWMNwYH\nedLzU8yx/RLjQidYeAkIcTnph/k98jCIHDMMPUPBMVtl7yRESq0MxooDQwDu\n9ZYCDfW1HZ8Y6/JvaldyrmZq9++B9aYrRSbLxwqYQXA7macnijYgsHOzC59H\nFHuM\r\n=WQqu\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCyAH0p7LLSUT2t/VSuodeUDEnstWgrRHAnTX1m2CPuSwIhAIZ9/dUYmi7H3YYuGor2BGnOlhhajXNqtvMHhZd8x3BK"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.0.1-cache.2_1568894009841_0.9783168793455979"},"_hasShrinkwrap":false},"9.0.1-cache.3":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.0.1-cache.3","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000","tiny-lru":"^6.0.1"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"gitHead":"4e34a69439a6beab4bfd5833d0f7baf493f6b391","readme":"# RESTful React\n\nBuilding React apps that interact with a backend API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of a React component.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Composability](#composability)\n    - [Full `Get` Component API](#full-get-component-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `Mutate`](#mutations-with-mutate)\n    - [Full `Mutate` Component API](#full-mutate-component-api)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n  - [Code Generation](#code-generation)\n    - [Usage](#usage)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n  - [Caching](#caching)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [Dogfooding](#dogfooding)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, RESTful React exposes a component, called `Get`. This component retrieves data, either on mount or later, and then handles error states, caching, loading states, and other cases for you. As such, you simply get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  <Get path=\"https://dog.ceo/api/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\n## Getting Started\n\nTo install and use this library, simply `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import Get from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\nRestful React ships with the following features that we think might be useful.\n\n### Global Configuration\n\nAPI endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `Get` components.\n\nConsider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nconst MyComponent = () => (\n  /* Make a request to https://dog.ceo/api/breeds/image/random\" */\n  <Get path=\"/breeds/image/random\">\n    {randomDogImage => <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}\n  </Get>\n);\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\ninterface RestfulProviderProps<T> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   * This can be a function if you want dynamically computed options each time.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Composability\n\n`Get` components can be composed together and request URLs are an accumulation of their collective path props. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n// Assuming we're using a RestfulProvider with base=\"https://my.web/api somewhere,\nimport React from \"react\";\nimport Get from \"restful-react\";\n\nexport default () => (\n  {/* Send a request to \"https://my.web/api/breeds */}\n  <Get path=\"/breeds\">\n    {data => {\n      return (\n        <div>\n          <h1>Random Image</h1>\n          {/*\n            Composes path with parent: sends request to https://my.web/api/breeds/image/random.\n            This happens because there is no preceding / to the path.\n          */}\n          <Get path=\"image/random\">\n            {image => <img alt=\"Random Image\" src={image && image.message} />}\n          </Get>\n\n          <h1>All Breeds</h1>\n\n          {/*\n            Composes path with parent: sends request to https://my.web/api/list\n            The preceding slash (/) ALWAYS queries the ROOT of the RestfulProvider's base.\n          */}\n          <Get path=\"/list\">\n            {list => (\n              <ul>{list && list.message.map(dogName => <li>{dogName}</li>)}</ul>\n            )}\n          </Get>\n        </div>\n      );\n    }}\n  </Get>\n);\n```\n\nFrom the above example, _not only_ does the path compose based on the nesting of each `Get`, but each `Get` _can_ override its parent with other props as well: including having _specific_ `requestOptions` if there was a valid use case.\n\nTo opt-out of this behavior `Get` components can use an alternative URL as their `base` prop.\n\n#### [Full `Get` Component API](src/Get.tsx#L50-L87)\n\n### Loading and Error States\n\n`Get` components pass down loading and error states to their children, to allow for state handling. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Spinner />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          {error ? (\n            \"OH NO!\"\n          ) : (\n            <>\n              <h1>\n                Here are all my {props.animal}\n                s!\n              </h1>\n              <ul>\n                {animals.map(animal => (\n                  <li>{animal}</li>\n                ))}\n              </ul>\n            </>\n          )}\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\nWithin [Operational UI](https://github.com/contiamo/operational-ui), all of our [`<Progress />`](https://operational-ui.netlify.com/#!/Progress) components support an `error` prop. For _even_ better request state handling, we can write:\n\n```jsx\nconst MyAnimalsList = props => (\n  <Get path={`/${props.animal}`}>\n    {(animals, { loading, error }) =>\n      loading ? (\n        <Progress error={error} />\n      ) : (\n        <div>\n          You should only see this after things are loaded.\n          <h1>\n            Here are all my {props.animal}\n            s!\n          </h1>\n          <ul>\n            {animals.map(animal => (\n              <li>{animal}</li>\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  </Get>\n);\n```\n\n### Lazy Fetching\n\nIt is possible to render a `Get` component and defer the fetch to a later stage. This is done with the `lazy` boolean prop. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\n<Get path=\"/unicorns\" lazy>\n  {(unicorns, states, { get }) => (\n    <div>\n      <h1>Are you ready?</h1>\n      <p>Are you ready to unleash all the magic? If yes, click this button!</p>\n      <button onClick={get}>GET UNICORNS!!!!!!</button>\n\n      {unicorns && (\n        <ul>\n          {unicorns.map((unicorn, index) => (\n            <li key={index}>{unicorn}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  )}\n</Get>\n```\n\nThe above example will display your UI, and then load unicorns on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or reshape. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `Get` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved data to the children. Consider,\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst myNestedData = props => (\n  <Get\n    path=\"/this-should-be-simpler\"\n    resolve={response => response.data.what.omg.how.map(singleThing => singleThing.name)}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I want</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\nRestful React exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => (\n  <Get path={`/search?q=${props.query}`} debounce>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nDebounce also accepts a number, which tells `Get` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => (\n-  <Get path={`/search?q=${props.query}`} debounce>\n+  <Get path={`/search?q=${props.query}`} debounce={200 /*ms*/}>\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\nconst SearchThis = props => (\n  <Get\n    path={`/search?q=${props.query}`}\n-   debounce={200}\n+   debounce={{ wait: 200, options: { leading: true, maxWait: 300, trailing: false } }}\n  >\n    {data => (\n      <div>\n        <h1>Here's all the things I search</h1>\n        <ul>{data.map(thing => <li>{thing}</li>)}</ul>\n      </div>\n    )}\n  </Get>\n);\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of RESTful React, each component exported is strongly typed, empowering developers through self-documenting APIs. As for _returned_ data, simply tell your data prop _what_ you expect, and it'll be available to you throughout your usage of `children`.\n\n![Using RESTful React in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `Get`, `Mutate` and `Poll` component is _generic_, having a type signature of `Get<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `Mutate`\n\nRestful React exposes an additional component called `Mutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit Restful React demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/30n66z45mq)\n\n```jsx\nconst Movies = ({ dispatch }) => (\n  <ul>\n    <Get path=\"/movies\">\n      {(movies, states, actions) =>\n        movies.map(movie => (\n          <li>\n            {movie.name}\n            <Mutate verb=\"DELETE\">\n              {(deleteMovie, { loading: isDeleting }) => (\n                <button onClick={() => deleteMovie(movie.id).then(() => dispatch(\"DELETED\"))} loading={isDeleting}>\n                  Delete!\n                </button>\n              )}\n            </Mutate>\n          </li>\n        ))\n      }\n    </Get>\n  </ul>\n);\n```\n\n`Mutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with available verbs and other self-documentation.\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise, that can then be used to update local component state, or dispatch an action, or do something else depending on your use case.\n\n#### [Full `Mutate` Component API](src/Mutate.tsx#L31-L47)\n\n### Polling with `Poll`\n\nRESTful React also exports a `Poll` component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\nNote the API similarities that we have already uncovered. In essence, `Poll`, `Get` and `Mutate` have near-identical APIs, allowing developers to quickly swap out `<Get />` for `<Poll />` calls and have the transition happen seamlessly. This is powerful in the world of an ever-changing startup that may have volatile requirements.\n\nIn addition to the `Get` component API, `Poll` also supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n  - the signature of this function is `(data: T, response: Response) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in Restful React, it is as simple as specifying a `wait` prop on your `Poll` component, provided your server implements the specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\nRestful React is able to generate _type-safe_ React components from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.d.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the specification\n\nTo enforce the best quality as possible of specification, we have integrate the amazing open-api linter from ibm ([OpenAPI Validator](https://github.com/IBM/openapi-validator)). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, just add `--validation` flag.\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of a `--file` allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything, usually your computer name)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open Terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite easy:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to Restful React's generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\nDo you have multiple backends? Do you need more control on the generated code? We have the solution!\n\n-> The `restful-react.config.js` (Note, all other flags will be ignored).\n\nTo activate this \"advanced mode\", just replace all flags with `--config restful-react.config.js` (or any filename that you want)\n\nFormat of the config:\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n  };\n}\n```\n\nExample:\n\n```js\n// restful-react.config.js\n\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n### Caching\n\nThis doesn't exist yet.\nFeel free to contribute a solution here.\n\nAn LRU cache would be nice.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### Dogfooding\n\nThis project works great when [dogfooded](https://www.google.com/search?q=dogfooding): I'd suggest creating a separate project somewhere (or using an existing one), and using your fork in your project. To do so, after cloning and `npm i`,\n\n- `npm link` inside of the root folder of this project,\n- go to your consumer project,\n- `npm link restful-react` in there, and `npm` will link the packages.\n\nYou can now `import Get from \"restful-react\"` and do all the things you'd like to do, including test and develop new features for the project to meet your use case.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.0.1-cache.3","_npmVersion":"6.4.1","_nodeVersion":"10.15.0","_npmUser":{"name":"stereobooster","email":"stereobooster@gmail.com"},"dist":{"integrity":"sha512-Zf6meLgj95pyQoohXlJhhNJpAkhIprQWnR26z0mFmyzTY+EjWzschfGKWbvsJmJQdwriZCbiV5YtJTwDOGNbvg==","shasum":"890bc22be6bc489aaec6c641e3a7773938937661","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.0.1-cache.3.tgz","fileCount":49,"unpackedSize":276567,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdg3y2CRA9TVsSAnZWagAALVIP/0xMkeaBUFsA5Pu+T4Xq\nJ6y3W/NYIEdS0hb3Ut6C8t17COhRu3bBPb13PFUDmY7zcBD4f0vyeCgKERlv\nUGrqMVMaZIHJ398TZNOgAzUdOYPl2ncz9OXGoLiMIBZFVV9ZeLxl8n6sERv0\n98BVkrlcEMEBGq5Z764RKvZZOYULy3aVIPo22cV18qVdyo8KhC1zHaEXat/5\nVQaShxiaphTluiFrF6bv73e1q66r+N78drhNftEtdQ9hBR/p74eSSn61d8mN\nSKGOMzdV8UxDnTm3RF78nYs/aNvDErRow/qdIzz4huE5/GueReLOFmUo6aFY\n0lCTp5RT0H2CrXxXA0bUGSakOQMXRRHraJFEQbHIOnh9J/VaHsMxJND7qsgP\nfIYq9nIemsCEkPT45p+66bzJlm2/JsldWKWfrXT6g5BsSx8YJrDTz4eVl9+h\nmkhZiy6C/xJN/9swgwXkC2KNNIjo1hKXVVlrLq3GaWzfXmTvqRIES2hX01V8\n4HkJszoMPbfxo6eFfs0hMnmYf7jI1EEKIu3PnX3HYofD011PdR5YJFL+NC+6\nKiOUsnMoH2s7v8qkcpEO5ymBvcSvEyjATVy8Z5foZGDQX2Aczsr2ibOfOA5T\nRaGngM8AWj3/XqgveciA1JoIt15FroW2qx+49mGlzmJ9oTHftviW5NFdah4k\nZewk\r\n=k+1o\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIAUSCEwoCdP89niKhMU3bVcyzyJZRjbv0H3NncX53kzRAiBfe3iKvZQWz+yjKu9YxPjekD1UHExHv5A6z/SmwtBikg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.0.1-cache.3_1568898229390_0.8043162470466383"},"_hasShrinkwrap":false},"9.1.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.1.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"gitHead":"7d885b327a1320a3d4eff86984d13b8f6cac6e95","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.1.0","_nodeVersion":"11.14.0","_npmVersion":"6.9.0","dist":{"integrity":"sha512-L+ZUj8IGuW2+o+X3s04bfLWIvQdiCe3Syz2Prwb77q4XDLrgBknOM//cvn0OpS8Qb/Pby6P4WzRpDd+14aaRdg==","shasum":"b23aebb8001c2ba3eed42f4bcf0f2e66102724e6","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.1.0.tgz","fileCount":49,"unpackedSize":272218,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdrXQLCRA9TVsSAnZWagAAE88P/2uxROcMXR3BkhDUeRXU\nvUc6V5W8Ww+l0OxNIUBMFoc8TsFIiJBtYrJyfVS/ic3nZ4NBSA4KUVFtSPX3\n6VMw4pIzbqEoFyeSUJyWR3m+/oweu8vFmeZqRNGXscxslFiZk0OIicAWNCJr\n08vbby/1P6yhwvvce+Tl6VIy2nPICwaMcJWQFKjMIiq8Ag9BG+GY4E6/olnL\nfe741LIhZbgsOVZ953fwh67o4Q71aUDDMQ+RNqiMznqxfl6zz5OUjos/JSFV\nGp1rVa4Efum+HJxtm4JqD2vUnaQwIRBo+Yjw6YzxLTFYnC8hfmmniKqn/LYJ\nu8e/GFAiSiCbA/KCgkeOiyhWghHcSMcqCA7Wc+LM9qkvl1aw9ESqkiPpf3se\nFXyaVQ2ghDNJEgC8mI6iIzHE0w+ZETWiRK8VGvF9E94cpPmQJhw2TNsKIq72\nfwcT7yVQcagomCseO/YQlERXtfZfINzpd8mwhmZGdDg7dfvX4WktE0tXETTw\n+2b3vHLdValIsO+a00uh+rs98VQFek912pEpVnWD4ps8btm07NeaGdmFbOie\nsyd/qTEMdp57rLkqCwjCv2sKWYiWC3fEryKMYNa9qmkM0N2uLRZdZzMQ4pHM\ntEAk5vQa5xcJT9ihctI7v7myCHbd58g3l53vaZ1xDTbxq267wpSDnfGZVilc\n5E2b\r\n=EFwM\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDuBokePuIHxhDWMWkyS9QfeayVVP34PJtvHRQZgBsctQIgUuJMSaL6VGdSITE5WfZ7RCy8M4XUhNPtHiE/g7dvnuo="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.1.0_1571648522777_0.9700873807472059"},"_hasShrinkwrap":false},"9.2.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.2.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react":"^16.8.4","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.4"},"gitHead":"ac07b715abaa7bc373a0c1878801f2b9e713571b","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.2.0","_nodeVersion":"11.14.0","_npmVersion":"6.9.0","dist":{"integrity":"sha512-tdQX4a264K7bj6gO6m5/nzM+krSdoHfaDBd91+DbAl8n5g7zHNMsaVKziBqg4LzkSNIbzOF2sl1c3+kDhualLA==","shasum":"4f73a8056b601aac610978cc418ed72cc6ee8207","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.2.0.tgz","fileCount":49,"unpackedSize":274539,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdsSdqCRA9TVsSAnZWagAAy30P/2XJwzcuYnZ0h/kPPWjC\nhgRcpXFrkuNw+Vipg+9iqB1TUYemFHXJWDLPgsKlqhFskHY30Z+PW5thTBnL\nMCq4JPgKw74Q0UD5UoJVgEmYSQW+uUXnXhDBdkOhelOdMd8pk8lxjvrjYaWS\nlTmfiNWMPHSNSh1RqbnnHIZNQH69G70sdg4M07a2JZEp6kiKuXbu5UXudcrM\nFFk+0s31m22w4AG+y+7ckn5ktEy+L/7Sl7Y40b/2VTGVrk1Iao8MMSjuCpQZ\niStJ7KC4RumhVHE42VVW4eaP6GO2B2dEulLBiuxm/MrqM0Vhgh7xR84VRIIa\nA0ASil9wy5qoGWQhCrUuQ4u8NUkx7pGPAVrozXJOybDXkZIA6J9ZWLLk9pvZ\nKL7adpQ8cSs1Um1uGXslHL7fVcQUOoODTRGEShDkNVZiaQn77hJ7mC6nvb4o\n/sQAhNMKKlPsRymaDA28nAdF+O3aH8WwQX01ItfvaouUJd1AOshRIcA2UFV9\nyhG3CZBXH3RAVTGQgKZjvq+ZWgeCHSrLlc26k+JotmM53xwxy1XsWQNk4DHP\n5w/dQ/LOtIHx7RHskA3KApIWMvcezMgwlPCyd/waYEAYsgk4sGQDhJmKv2OF\nikhlQ5cYG41Gh40ftK5wwllJli0tEUEZyRQsX3lie7nnyLAUPLDI8XBnyz1m\nh2gm\r\n=uU66\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIAdRJXWWnBG0IXQ/QdTD4E0FM9vOacGGa+ZIYxgOqVe6AiEAzEYE/MmQN8gmGculEBAyctSVK7lJDJ/oRLxThyFg7R4="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.2.0_1571891049926_0.984439623542049"},"_hasShrinkwrap":false},"9.2.0-gb9a3f52":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.2.0-gb9a3f52","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react-dom":"^16.8.5","react":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":">=16.8.5"},"readme":"# `restful-react`\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overriden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most poweful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project, clone the repo and then `yarn watch` to get into dev mode. There are existing tests against which you can test the library. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"b9a3f52b47271116c65d60b50d8b603c5c6dc461","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.2.0-gb9a3f52","_nodeVersion":"12.13.0","_npmVersion":"6.12.0","dist":{"integrity":"sha512-G5CF9W18BAQpfgOn613oMQb9SX8pnAzFFu01iE15/odY/486qnd+2MEEgF9t51xactS9IQE/vCutB+sSyNw5tg==","shasum":"6e01796b81d99208d6e8d903c82323bdea385a16","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.2.0-gb9a3f52.tgz","fileCount":49,"unpackedSize":276728,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdzV4VCRA9TVsSAnZWagAAgsoP/Rx33+BLHDxeYbMxmMAt\nNpNN608bkB3kp9rVXaEbhiGQqtKFp6S5QvclNz4F1Qr/pSgLuU6Mph3kkLh0\n0rN2JhSJVSgD8nVLUlNIs/UsLByscoegEZpKTNGxG+kwfsuyrUQRhnzRdIDp\n+IbtV0wLMlVlX5dzP6kS8yvf90ZdU3FGk+uF9jH1x9EL/iwttW+Yn+kl6bgm\nIuKvnRu+Hc0C24OEY3Ik+W60Z9TywZpZu9Oza+d6n5vWIIQ3XgkOhaax4D9z\naWR1vRUldP/R4T6CGAZtdYLQDxWsaxJvVHf2qDuWB7q9Q/raslpKER1WE/Uf\nKXe8oUgYQaC6MtfBddz8Xx0lTb2mFq3ttkbspC3k92Ka+RMWxf/nU0JUowdU\ngMZn9aKN6nK9zpT+nkYTcj5rFWPHyYg50P4HSdGuo5WaoBIAjomZBkJuy73F\nDENCwSK+DMRDYh56+vKk6phPTDR9kwKWOb/dC863vfbY3L9nV0rJxOtZAEH/\nPeosZ3uTFomZlDcNKiWb4EJ2ZsqKtPkVsXEiQ7rBpVm6FzgEBkmgT8Impdfz\nSwj9JwFKVw0sUX/3r9tfcslk1lW91bbdQLf/dstdn/yU8ezaBiikVVKDpk1d\nSArje4NLb4tBkQlYKT0zdRSX3zGIkPix08Ww87e909mcVLrneFjoUuo+Lt/G\nXesC\r\n=OoS5\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCN74bsv3p5HskO/hF4Nxu/r1siysjnksrpiran73H5FgIhAM2DWvPWb05ai1oKB7MzMGHerDPahCAVr7EZnS+QAHhv"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.2.0-gb9a3f52_1573740052521_0.6738537425864015"},"_hasShrinkwrap":false},"9.3.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.3.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node lib/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react-dom":"^16.8.5","react":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^0.12.0","qs":"^6.6.0","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"30bf341e40d01b7fcc06effa4f558ea452b5ebc8","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.3.0","_nodeVersion":"12.13.0","_npmVersion":"6.12.0","dist":{"integrity":"sha512-gdJzdUbyKJamppRCiEF21O6/B3i4CB7pflH6Z5RQnXAOuTx4DD2+ytnxZQol6zv/UBDCRKIXy5t1fVXeprtOtA==","shasum":"98ad695bf3fd3105b3161b53e42a2b6093f26953","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.3.0.tgz","fileCount":49,"unpackedSize":284594,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJd19FqCRA9TVsSAnZWagAAzB8P/3xxkpB75EiQn3mKVh4s\nZLSfup70KbJbdntTDl1lV3RzVmzZxwg7v23LaUUJuGvVs6RoKwjncdcLSgI9\n2AGDDZFmr3J60O/65Ty7yClavqDQZTEbWrxqN81w3V/6vb5JYLQq5bmx8V4T\nKKFX9KMKlt+EyBKXiGwnXs/8RlB3VRh8tSQLtEfyM0yRQCAD+ZTAWIO2Hle1\n13ClqrxgX8DtjPP09OCzuRJv1tl8zexg5wcu9kLUb49so2Ebh6RjDxR4yn19\np0ZNzCy4jKTgyhNJAZs8OlfNNE/jpzQcRGeHNwyeEDwxHikmtyS2jIiBYBen\nJSBZDj8x0FfEY6EY0u1x6biW4Icma+tOU4YTL+1ARh1nRY/g5waMj/MU3ygu\nWUOs2UPEEQAxOe96G70HhhElIah+iJhloZnqETSud58h6chF/y8KZ+SZCSsU\nvr2ylx7+02jOWc+mLtFmHeFIVKahwbdNl2OGd458Y/E3MuQ8bCJoH7XTMqJU\nBPezylaHZb6egyhkBXN2sTRY9xC7YijjeyAQdJeChJZ9QjLp6A3hGRmuHtP1\nE7zZvnc1EAcPfdQ2l0Kmb77MWTaiJvaUAZ8UJC2KE0lcaCF0/m7VUzghHxpV\nN3paNlks8DHs5w87Ir2n5FdjQm2WXsbuG8fRqf+SwLnO2sImBpL6SkuXZIIV\n8xlq\r\n=FPTW\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQD3BBODDHZ5yfldtVz4PnVfDTTkAd4gz5e7XjPLXpc5LQIgMiQvC8Fr8pQRFxIbUDUhN5yfxSUoBy6FNphZpgvko48="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"tejaskumar","email":"tejas@tejas.qa"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.3.0_1574424937872_0.06960493583829086"},"_hasShrinkwrap":false},"9.4.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.4.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node lib/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react":"^16.8.5","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^1.3.0","qs":"^6.6.0","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.4.0","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-et5H75MdPvwUMDieLjWNf14x3kdS+t6RzGHUVSTXLvVZu6htf6Vjv2rI5/7w6pQ4JjStNKx7mSg4vz1iqGHR+Q==","shasum":"ee3290299e36016aba2521b9a0016fe8c4204e59","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.4.0.tgz","fileCount":49,"unpackedSize":287435,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJd28ljCRA9TVsSAnZWagAAjgMQAIb58fFUPydmTszOTR3X\nYjo1HeBb37rGH5w+N74fEoRjrciHw2h3BHoO4PDI+ZvqIBkK56vyS4b2+XE1\nl1GU18irkTjEfLZwrE6Z+PiaHDoVVmjCa8qK+Qh/JE4wo3RcJDT/BUhtq0O0\nP15iTYSIUnaC+nLgJbsIaqqKuuStyYnsaFfUkj2yDaAqIG7WoZriC7oK/UDa\nNfUJEI8CzjlmAu605t8J4optboJiuKN14HD39fIeEno5LGo+Ov2QUoH9hwAZ\niNI2WefiD9YckhKbquBy/e8+ZxUbcSBq3NUxTB5x9PJvrmfL1W9UNwXp84a5\nUT4qqNIsJT4qgt2xK6wQQgOlUY0AwO8DoSfKjJ3dDwZ1Wv/w8Wnasi4jG1Or\nF3T00BVZbUmy+6RJWryOFmTatiVMgdRH8LDkDqv8xzD4WKD90CQWBvYMSY1l\n0AOW/JgmYqERGRcZ8KE7C9XC1E8AXtZfm29y5d4lRsOoF4CKrGdVL1RcUfaP\nzDJbu9uTj5BKazDxy1I8GFPKsw3XVkMEQ23qzXTyNnkF+CJfgMroiBkujEj9\nzdw9f5W7mmIxsrBer+q5XURugLSd876txOyjfZe1WCgxFgN7Yu4OAnXzwf6z\nuqpE8AgBb/SpvSZ99x4A/e3Xw3eVTX8WKaqsGY5eBbrVmSVjKYrNANG77rig\n22ui\r\n=pSzL\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICi+WZvPdo64aCx1WoMSCV7Us6UP5dMd4gZycmjD98gnAiBcUXhwYEFOaKbeRYWvymO7dKtQRSO95xoa+EjOKkl2QQ=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.4.0_1574685027231_0.6028590466674495"},"_hasShrinkwrap":false},"9.4.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.4.1","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node lib/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react":"^16.8.5","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^1.3.0","qs":"^6.6.0","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.4.1","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-D2G11r2kW0/zPJV5mb1yVYgE60B7i0bgL1ML0HplG9CHdVjGH92f8BErnayRjCu9KYLF6HRfcQFel7NXowzTww==","shasum":"90cd3c1d9d62ce3c557614fae93b633402cefb5c","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.4.1.tgz","fileCount":49,"unpackedSize":287856,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJd8JkHCRA9TVsSAnZWagAA+iIP/3jyG5r5OpHYwt72RZUN\nH9Do9/kRnk5pXWd51/0VDCw9Qka+qxHhUOrKczDfgbjOEFfr9lG03W8DJJzT\n+sYlWyRdnUvJugXx7KDjVN85lWo0mrB/CHC+vzyzgvw9qPTLl6WviLn45NJQ\nqNBIENGMlJK6DUsaGwIqHSIvUlPn2SkxKQc2rHpXiFxPYP/+LX6qR6K1adcB\npZ8CkTuVlQz0mNvwb7Zv6GZRBOphHYv0r5QEoRM+HEHtePAKQAyQcnfci160\nnlyelAx3bZDsThtMoP1TiWC+Dlw37/Ew6W/hCMu+rgGPnLcs/BJ9sjHoh8Au\nE8qWSJgjq8aMF0t4ekddCxxDA7woS8G7TTw2XHWNGBiM3w9JPO45otHoP62l\n6e4AwdGxJDI+hIv4JB2jQHv0JZoewSMMqc23/TpxmOL6brs1PymVs9rC3yxb\n9eTQCOd1pRTnmz+HWmo9tuLrcW1XDL3WX1WLLwYgK3AkuQruKpKaIlxCVjzL\ncqpf0G/g3RHIfkFJzEaiMmc1dqbUIVVhJ6xI6RVEwbC5vXCAH4EkVzZ2Cdu7\ntEHr2ly3TXb4rL7jzy0aGb6zgHcnn5PnxfRDZlZkEb3xQyZt4DnbjhO6OQLx\n5MNg9u91B3va+CjmEfFEAFvEaMIxfTqSGF3iIN148GEyFD8ufeSe/RLYVCvq\nQ5c8\r\n=145C\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIA7FQcMLn+qoC+rYaD8NCsq4KHo+ececzKEUwgK4hjmvAiAB2hFr8VYCi1z+10K85ozLGL7nakCHzaTxKUZmwMVlnA=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.4.1_1576048902952_0.36011842904915925"},"_hasShrinkwrap":false},"9.4.2":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.4.2","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node lib/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react":"^16.8.5","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^1.3.0","qs":"^6.6.0","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.4.2","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-GZRKzqPYQqZ8hOSRXpeeL/gsBfnn5zpU6zI8EVkFhOx2kzv3yiIKkVe3h0S1IKsueQiyWm7J6vtv8gBFV/kUsw==","shasum":"f66db3cba1c915b079f96a91420264c804b38b53","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.4.2.tgz","fileCount":49,"unpackedSize":290070,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJd8JvfCRA9TVsSAnZWagAAAGgP/3gGqAsKx3paR4R0vxWY\nmM+S6qE1CTIDW9bBL8q2x2W24M0zk07xxVsqhdjnaYwX0y064ZVtDU7CEhcL\nW8djBJ2DFumwKOzFFwFqPyovC+0FtjwRmSBMuYESzP8LcFBUADaJW4pjVe4r\ngi/LEPmjMc9V/R3yyY7Jq3LB/inGv3mWtDv7e9ufwKazL/oVZ2CkYw6B6PQy\nWVUHVkZSM4Nlj2hmUeFlVyOfHBuikMtDPOcE93wD6yycE0ya9IzY+XAtrvDS\ntgOtc14L3ixNmBHRi1L/9IjfoUEm2uycxBexJDz/l8CdrzwgxONn1pP0b9bz\n3QhN4lW1kSwAx4DYrdOHEPeqLMZtMc7zte01epIyYihVI+SpL+JqsWFG7VRT\nRbnEhznaK02K8WcInTJjjhZMqz4z5vCebMygGUj43OLvRD0zUWUgaj5UGD4l\nyQdKnbVz++Na4PJb9TWpCCBQBhrUen1KMGjsM2t40kX5vtZpjz2MYVinZNZn\nD0S+YG+ySOuA1dbDDUu7c1AEVYsNMEDzT0VBhCIkBYFAma+Iqn4Eu5j1zE1t\nR8Volb9/uLECC2RMXYj90oTB93Xyqu+w/KjUl4H6JxgyKYfbJaSU3A4M+a7o\n4H05oZXSmuJEJdM7oTY/fd9xGpIGXFN8nABL8CMCudAq/SpFXCP3AzG67jVc\nelBu\r\n=XwvA\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIAEN1u494qc6oSyx0bIos+LG2kt3Zt79JyzWhmUOXYA0AiEAqHQTJ+ClO0BrpfHvkIAa0FV5Hx20R3I8e2uTo9C2gJY="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.4.2_1576049631170_0.590402389547467"},"_hasShrinkwrap":false},"9.5.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.5.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node lib/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react":"^16.8.5","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^1.3.0","qs":"^6.6.0","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.5.0","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-UyRNp+ku206Zn6tWiHJ2RThif8UgNKq1lBQQAGJYF5kbOmJKIVJ2nUUDKZPCJIOp3wsDgUh6JUQhlFOcXXgvCg==","shasum":"86881ca562ce6701dc3bad51949841c0118d674b","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.5.0.tgz","fileCount":49,"unpackedSize":294532,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJd88WVCRA9TVsSAnZWagAAtCMP/3ec/yzaK6mPCxRZtWWE\nsOVMM2kee7AUaf3/CgVHONpAIrdWPqA0G31z4xeUUvbnoWjbyjjYVig6/tfb\n49WU2OgvcfeIxPGWlBNNv13KoLyu3Xdx4j5iNQyLFZzTA8ucSAWAqPq8rg7B\n5AyxPSgInBIIvKNeKn9dPNHIjnsx20Hrs4oq8+NxRXKSLRJzk3vHNvs309Ig\nN024FCrSiYuVgSv0n57/Zq+XYl4cE45Qhpu5XTXEyEUZXq60yFDmnbm9NgWy\nZzDn3PcdhktJeZ548JAHwjcoqm63Hjdg75qSayif3D80c/ZKHzBbUwSc0rNH\n6/gpJmLM6/3ZJOYstZczkaMQNmQhG2Q40XSrUG+X9lZd6BaVSCZqwTCy5T83\n6QRlS8Rkc5eBhKQC8QTmjcAKagHlVs/arfjTyDxh13OKArdtZTEQUa2WsPAH\nJQzXRoVdSQWupjrfA6jySukJDZ9pGAs9oMiLHUbWI63RlUbzQtI2wcDlidWl\nDleloM725CeRYwIrPrvMfRpZ+EVfU/q0BfzxeFlgCBRtFwfvvso71NGRaeqd\nFA2+fQoY1t/5eOTyDNrYXWmUpwN1Yd1MQkLWwQTRBmwqgJ4b6xcI1dMuNaxJ\nu4LWsZSICf46FY3A8c39CzNNnjZPKMLzOv1xEtmDWnbr8dQQiQyYpcYm1cW8\n9ZcV\r\n=8NuH\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCEylrrJrIMZzhsNHxTLz/9xcwEB+BfO7qMqQrnNq/KHQIhAP8ezWZS5CVfNJOQFtr3/7VIKHF8QGS/FzBCyV7hnER4"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.5.0_1576256917389_0.9259178525581342"},"_hasShrinkwrap":false},"9.6.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.6.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node lib/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react":"^16.8.5","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^1.3.0","qs":"^6.6.0","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.6.0","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-AmBi2+M8T86KPdOq41zOsqPGcUJ0AeBmykqhzSYB3dt1REDT/P2RmcydoXZMhQgGEvktJK334wNS5jgTKPnxBg==","shasum":"2c35a6aef6fa1f9990ed9925650b6c2312e965a6","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.6.0.tgz","fileCount":49,"unpackedSize":298472,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJd91hsCRA9TVsSAnZWagAA72AP/RqYAzNPDuvWfCM0bYqi\nV+kKeEBtkpbgHhBwjYL5e6xRv4ffG1ertiXjdgNw/wmY3m/Y6hRSNtmXPfw/\nbWzDmEtxZXY88bV8qBBeeLF82EaEk++yYfUjC+7qvXIu+Ge7aDWiFOVXEV1Z\nOLREZkIqkBzH8B5G1wP9WyVkqJjj34VctBiTk6It8gSgXyoB4yprMV52uoBi\nkhQHYc9z8m/ySPvyMaq1w2jyhdlGy0j3WpsXSr+sXT2hlzhnB1jlMR7JGYq1\nWJykhYCw09P7QSKh8kSI3fLdwogu7Bkw5YmgaFQZa97zaKkYV6t9GPdUOxIa\n5NJ0YM7iBAAp4ykzbRPKLB+odjRSDCp0wUEDfkU9Lqgm8ib5Oi7/T4rU/RjC\nvi1WyhVwSv6YVwVtH1sQxDBYLmm28JaWg41nv8nHGItlUg6MZJT9qTJdSO24\nLQxuOxRTDRunOXpYXE0trwjgHjPy4dn89RE/b7d3rJdr9uQNo81gIVkfZLPu\n1owcETybD1Bden7VpBnpSbnwbkjfvl5jEGo3nUSZ2fCWnFYoNRrJ1CuAzJU/\nSdiyKgGBfeDjXtOtE7z2L2+2Wj2s5dDUS7QrBkmxAEV3hX60VL0IPwMT0ePs\nlxnP9/8PB1+QFiNhd7nyZPgWu3/B3M5+P2PCYbl3dnSteTWePrviVKLq5iSw\nBir2\r\n=hPta\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCbIjrBbQWRpDGnynbcmccCBQHEZhoSyQS2GaCNMxXfXwIhANILnABnFNlryLYUOJKD5G3GDq1Z1298EkIMJ+HRYEGT"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.6.0_1576491115557_0.2364212394375378"},"_hasShrinkwrap":false},"9.6.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.6.1","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node lib/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react":"^16.8.5","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^1.3.0","qs":"^6.6.0","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.6.1","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-aAlMi2urFSKGViWMpoVuydYNjNsJY9uAZWQ32WzPpvmIXosuAyKUjNZ7BYEu3QkXpgemAmEI4VYP0tbSM7ughQ==","shasum":"86f88c0c1aadea6bb773023156f4d37a6628662d","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.6.1.tgz","fileCount":49,"unpackedSize":298619,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeAHgMCRA9TVsSAnZWagAA0xoP/RBjVqaPoBs+Eo55oteU\nL+TbfkIfqAIvr2GTIf+ytYwWPEF5TMfb55zSjbYYWJuUEGWmRVg+APR39WiJ\nkxDNmf+Guk7qcmJgQB4z7P3BPFaU/m/wmBbXMtf/gVmr+aBVTEDqa2ZSnjVC\nluMxeVWuWR7sEbhGxVqVsvPOE+Ra0aDk8LS5FYYaErLfNHBEjFYK2TeE3A1D\nJrEazsMtpVMQ3mZBRVWpvQMxis4PiYiRmInejYooDRJF4el4siEjIKuE1+Ui\n+t09vYPKmFsldZsx+chjgzagnjdMXp7QrYHMRL/R0jaD+Nok4FK5m9kyIF7Z\nHc1QDLrsGoYHILpFaXt8FtMpRByGKQv28BqagvsW8H3ZPUsf3V4ny+UxxGIP\nQAK5bNWhBVk2NqNMKuCXYQ6si8JM1cFVS3ccuOIY4bdDptO9rVloXT0EODtk\nmDpgXrvZW6cxMgobQKaVjsHrHfQfGi8Pi57mD2nK++m0NfYGI9wyWU2zX3Vn\nn4GpVXl9CpRrlhyYqnXDolTB3lP+LLtQMaAC8r5cjAIo+MLzyKo7pp+RYd6K\n7sheralbqW1+Yx5omTU7BQu80/iJFvsJJaUfvWpq9YyzZK7ePvjMY9gFNk41\nbTGP3TUtGwBCwWe5C55/qUkfKFiVVEAfhKNuaC6bxGpFKBnDCANMuJRDZIsz\neeig\r\n=kT/d\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQC66DqN/Jioe8lSNDG7dUbuHQrVTLzvjeOKgW1H52KokAIhAIPoJGxA4asRFFNFAKeafTUJGlntPvrYaR+tQndjXj4k"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.6.1_1577089035957_0.48378005647710687"},"_hasShrinkwrap":false},"9.6.2":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.6.2","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node lib/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react":"^16.8.5","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^1.3.0","qs":"^6.6.0","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.6.2","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-TMJpTrzj/qH+HAjJNG3gfp8oVjq5lTQtJ9fxxrqkMwNvM2JMEklmOHkIa90y0X4ofcfoGbmHU3a3yGtPdxgcqg==","shasum":"62eff1338cf3d6b4f4f581afaf1c84661cbec6a7","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.6.2.tgz","fileCount":49,"unpackedSize":298907,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeF1FHCRA9TVsSAnZWagAAJtoP/ja0EIHzOzJ/qVC0GXVP\nfjy63z1xbX5IwELE9loZic5oZFHlg2Xhp01qMHcIEFvJP5FrP87waR3QBeFJ\n79JEvkzfQ1HTvkyw0mYMKqI3+V2KNBotzoespKg9NROjkpFLaXZ0857FAaLv\nkbcMqHyYQB+dUHWNPEDVThyeDu11FtkirocfwyPXj31tIAKA48M6yENzQS15\n2SGTM1Gjg2Ustuo4OOuAkJxzY0YH+/XHhYN8vXOWFkp+kDlXm/1MSfrRMlHX\nYE/GmBcDImy8wAMkhY52qQ8IrueT3DvxmCCZZ/fN5CvNppjK0n2iRZ9Yj9m0\n32sCBmbeTJnw/7AfzFWR2RdNwaL4+agpn8Oeq9qiscp7ifErwIat7M8TSjw3\nEqw2wfExWptMeIQne7Spy/utEFnrVIss1ahcb+Ds61s0RMvZkk+EQIdBWfd3\ncOvBAuGpQ3bMeUATGOCTEb7OBAi3dHuPOVEXthwQJAuIm5Hncl6pqo//pgar\nhphN8YcVt4PQ2o9vhJBucpb0ygLl/3TbtXaw9Awr/rOLPeTqqXPSo8+bec5a\nOCNOWRSdfL6bJAL5S8xLlI8dCDDRx6SXTYt/TjHU0v3olrN9FCeK8DzwxN7B\nd0ijhS9ZxqSSAP/39wkzYF0Di/25z6fk563C86qYbfHxfAOm1kWvvuxLkCMH\nsjuc\r\n=SPyY\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIA1a3yLe7K0J4gmIOcwI4K4A7+eEwM2MC2A4BBkQ9GHqAiEAwWWjVZrSI5huh4v/9yfjM0ERTep2Sm3eKESQCphlgEc="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.6.2_1578586439254_0.7349732784141285"},"_hasShrinkwrap":false},"9.7.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.7.0","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node lib/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"devDependencies":{"@operational/scripts":"1.4.0-1c795b9","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"0.0.44","@types/lodash":"^4.14.123","@types/nock":"^9.3.1","@types/node":"^11.11.3","@types/qs":"^6.5.2","@types/react":"^16.8.8","@types/react-dom":"^16.8.3","@types/request":"^2.48.1","@types/yamljs":"^0.2.30","auto-changelog":"^1.11.0","danger":"^4.0.1","doctoc":"^1.4.0","husky":"^0.14.3","isomorphic-fetch":"^2.2.1","jest":"^24.8.0","jest-dom":"^3.1.3","lint-staged":"^7.2.0","nock":"^10.0.6","npm-run-all":"^4.1.5","prettier":"^1.16.4","react":"^16.8.5","react-dom":"^16.8.5","react-hooks-testing-library":"^0.5.0","react-test-renderer":"^16.8.6","react-testing-library":"^7.0.0","rollup":"^0.67.3","rollup-plugin-typescript2":"^0.20.1","ts-jest":"^23.1.4","tslint":"^5.10.0","tslint-config-prettier":"^1.13.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.3.4000"},"dependencies":{"case":"^1.6.1","chalk":"^2.4.2","commander":"^2.19.0","ibm-openapi-validator":"^0.3.1","inquirer":"^6.2.2","lodash":"^4.17.11","openapi3-ts":"^1.3.0","qs":"^6.6.0","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^3.2.14","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.7.0","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-IlWfk5ApBxVzkGi/GJmY2OATeI25YhmA4z8eqV9/uYGqm1QgdEaB3XMwpc9+ia+Ej654aNv2NvOcegEF1ylbyw==","shasum":"6cb467f5054595b67592b324a3f5b4d8d7761f3c","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.7.0.tgz","fileCount":49,"unpackedSize":299541,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeF1m1CRA9TVsSAnZWagAAKd0P/jIYoB8Cw1CCxjrx9q4Q\n3OGVgTplAdmexV8+GR27YKLCib9U47+OYjnXJdv6jV+UC/Ixhhbym1/kKeSb\nySF631UqJiFvA+DwPMVvN3svR2ngkO0vvF/Dg7MFHYnyyP3ab6afSx31HKpo\nbJ/TRtcXcCmvVk0yjI712i+rYgSjr/laRdis1HbMq+vsHq/Vd2Ge8Cj3R0Ro\nHvbHBK5y0fJnMnKSCa+YLdA1gY3bVG73Ryh9NjzNzcRhLQW0GSodyXOr4j3o\nAsyUchGsbNXiFtKlpumB/BUK4ZOAmyc+ntQb9YLbM1ILcQ2GUMX8mgwoMRW9\ndGROxP6Sk9RxpMi+HlmySQnp1C7GjsKdAxu6gLERJ9RxNg2AsWMjPTcZoomU\n6g+mWw0xvzdAV6NYttsRN/PyEHR+VCZPyP/NDWb5V/rkUNh4Y5C1KqINsAU3\n/+FO3nnqo2KYARaBHcwtUzrj0Z2xdPgouNvvTnsKzjz6kW+ZXuCyx+ygZHqh\nSVLJEgo2MbjJOLY+MOTfqgSIA3FPpORj7JKjEqui+rP9wTZoXBFDKGiHJBa5\ni3TVQ4wMCW0W5E85okHOqmANQgDwtKGuWZA30A56lICAoHREbg81n1IYhv+A\nnNRXiRrXwUYIW4Ie7SwGrLv4Gqm8QpzcGBPO4Wzad5BrLAnwEHScBo3a4+i+\nEj8M\r\n=u6Rt\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIAGKnZBLpV2ayI0UieCBasio0hLR5WlNoVLy8qf7np87AiEApODWrg0LKN0CbfzBbNeBJijQEtdDxpC0ZR8dpuhs5Bg="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.7.0_1578588596329_0.5474493074648006"},"_hasShrinkwrap":false},"9.7.1":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.7.1","main":"lib/index.js","license":"MIT","bin":{"restful-react":"lib/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"operational-scripts start","test":"operational-scripts test","build":"operational-scripts build --for npm && rollup -c rollup.config.js","preversion":"npm run build","version":"auto-changelog -p && git add CHANGELOG.md","lint":"tslint src/**/*{ts,tsx} --project .","prepublishOnly":"operational-scripts prepare && rollup -c rollup.config.js","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node lib/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node lib/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node lib/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node lib/bin/restful-react.js import --config examples/restful-react.config.js"},"husky":{"hooks":{"pre-commit":"operational-scripts precommit"}},"devDependencies":{"@operational/scripts":"^2.0.0","@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","@wessberg/rollup-plugin-ts":"^1.2.6","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","jest":"^24.9.0","lint-staged":"^9.5.0","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","ts-jest":"^24.3.0","tslint":"^5.20.1","tslint-config-prettier":"^1.18.0","tslint-plugin-blank-line":"^0.0.9","typescript":"^3.7.4"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.7.1","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-2eaaVI0QBWu0P6Bqp+6Rho6Ub9nDD0gjG/gAn9qOQdOrfXM3u0Ecc3spklFFVfeg756b7L746BnZxullr1r6vA==","shasum":"2e1b73883d90177291e42bd428b0efd3ad27f139","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.7.1.tgz","fileCount":49,"unpackedSize":305559,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeHGBKCRA9TVsSAnZWagAA1GoP/2POHvRHcsGZHUUCMA1n\nt43BDUr1Wd8scKg4S7N4eh+eOdd7I4fTnfoiyoG57WFGpq0T4Hc1UeuI7xt4\nSe90Uby1+JiRkiDEysKiBeQ6bPNKK9lM9TS0mEqm2yWJnID/a3TEF0qlSAyE\nhmciXxFjdxb7JS25PKg+AToQS1aDPk3YUz9ukZ36rINA8SMsS7374NcgOFP3\nbnsMUUZEHH+KzJxWcca0EjxKW2pGnW60zKD6sud2MTft5fIGaCRCxY8O5VvA\n4AjwnO/Ie/3FxY1AR3hX1QK7HiKezom4441mtzekZOtFRgiDRsO8vV4MmP1z\nctlpmW0dVOdbipyX/to/CGuQloWlFwl8DYHJ10AVahXHItN7w6tZfUIQRg6S\nb+s53XV2PWZ8XoKp5qtTMGijmDGyOYOJ3ycXhTGKWFYf+/oVjyDAtdkAVL3P\nt36/Y4pgSB0NzrRnkNfe//XLK5Xz8sm6s69I9AS6ZSzzSGwzT599jGrqTtN8\nytAtvqb2hAYY6JFf/SWtMdpIj5mc5nTzxWVIHcfRS8Ud457j4Yk2saB46i0Y\nCZBY+fX79I4rvm0EcMdr9ifrkcF2RA0REqOtvJWY2RULd8kGRpjnfquz57Dx\nGsfztnW5oqBulweBGKfA3YrFedTURPGzMh5UAlvoacuay7fcgul3svyzNbKZ\n7uv6\r\n=D5YZ\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICRzikcNreUWcuhpgGPJgdOu+H5E/L56cKUPsXVmX42zAiEA8vg6HjDiiSUF1tJKsqdzmmRneLH3IzGAmlzHqm8OuaU="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.7.1_1578917961815_0.46214626063175324"},"_hasShrinkwrap":false},"9.7.1-3-gc0047cb":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.7.1-3-gc0047cb","main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","license":"MIT","bin":{"restful-react":"dist/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","prepare":"tsdx build","version":"auto-changelog -p && git add CHANGELOG.md","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslib":"^1.10.0","tslint":"^5.20.1","typescript":"^3.7.4"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.7.1-3-gc0047cb","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-+oXZrPmVKb+baUSEU9lzrucc51JZ3Dqa9u0GYjuFRIpTfEVht9JuYACx1x2KyJMYAdWiS16u631LfyPGkehvHg==","shasum":"b1e821d0a268e3da60eb502b18c68e38dd87c197","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.7.1-3-gc0047cb.tgz","fileCount":55,"unpackedSize":428739,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeHYXqCRA9TVsSAnZWagAAcHAQAJQ6kVvJle8Mx068NHZ2\ndGTI6QATG51NyaizBR67pFSKQ9wTO4IqXtUVkLI58GGWNPoRHlNtP8epBJ+8\nWFeJDmuBDGahOPuYebotlWjEl4gocx4UqXgzU03DAuyQ+zS3c2uybd0HEcXl\nk/R1i7Z4ZPvEpKEvAtQOpTXs9G4Bt7n5vyhWMZZ/b0W9pJvOJ8UK+A6UlOeL\n+qIrspiMmLNSzO0sb+I4SLXZxXazqt4Y3niJHb4iui/W1ylgUnVdC0wmsMMr\na1/2TR7yq3iPNzVd7y7NIQ6CfoIZgLg9ojQg2gYD5ljm0Lf2KZNwQ2AyAiYv\nt/tYtfw7bQnNp0wTxb1DRGdiSwQGlAXV5Js5dzM0Xg6IJ3B+RWRhxuYPE2tV\nxSm7Re3ak8CmIwO2FvZlny5hgYcfYa3xUKC12QRz6uPO0P1CZtvLexvxWbfv\nbR8e4Zv92E5D1jACSC2Ff2YYZHAzUISfOu84iCgLNO0aXiZU3spzahhhggN6\nz87xgrhuId1O4EhvlN4xIInfRDvu3L6GaVwqR2l/qqTn92PwuM1lrtFyQh2g\nldPPeFvJMIVK18i7XXuY/T5xvNajTNUpUbu0q33xSXA5eELLEI/rwMrMW9Lq\nnFe2eIzYLVxwS6UkzjMKohQWemhpnwAt8Te5Sg+aCQ6uRupItIDr6fmfI6NA\n6XXz\r\n=OU/q\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDx/c6oGbyc0VTQAXlvGcpXimE36oENqPnoeuA+lk/gKgIgJm7yAtkUHBjqDdDtHndFuHBBtrzDAMcHUZ3Oo8H+x0I="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.7.1-3-gc0047cb_1578993129443_0.7780006974700724"},"_hasShrinkwrap":false},"9.7.1-6-g0969004":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.7.1-6-g0969004","main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","license":"MIT","bin":{"restful-react":"dist/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","prepare":"tsdx build","version":"auto-changelog -p && git add CHANGELOG.md","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslib":"^1.10.0","tslint":"^5.20.1","typescript":"^3.7.4"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.7.1-6-g0969004","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-fv670P/8t7PbJkD0w3yKd1ZVUqMb8JEtlAnuQT1SrkouH8BIN4zmxRomJnXYUkEeGVGqhCF7Rwlu6XfGi1YhXQ==","shasum":"694294fd744f8863f2a3691e79038b147b9a34f1","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.7.1-6-g0969004.tgz","fileCount":55,"unpackedSize":488729,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeHZTzCRA9TVsSAnZWagAAkNQQAIeFy08wwNTV/KTwETTm\ny+J8qymfQY+fnUYguAmSEd2SkKAqCHgEQ7mPPuv92kwJoBhbhfiXnKEOK6UY\n3zpimA7bR9eHUaHdykmK8z8OeMAB8CMCe0AyY0OJwkCpLyg3yodRRrj4ieIb\n0YJTOfHg3y6xLuluXHy2SUPed4a2pqVnw5M5wIzeYjevrhFAXVbwCpa35wB4\ny7aKcOQ11v1nD6Hgsvvdgkdm3UHNLGwB73yNuZem5GIft3OTDhw4+F6hXDwr\nGxeRXmNQCPbSVkLGQX2Y05hN+dW+gSCoq7xSf1Ct5SYCeibunalarIVNBbiD\n1NO53fznKQLby4hZXS3b0csEXQ3ys9mTMF3DZQ73rWNUoe7L1MM8eqjZpqvc\n/q/cmezCOEp2ZS4NZGs8IzuoIhqaOdrRqaSLidsPAUpc+JMMrgd1vY1YF6Wy\ndA777blyGxoctvd5lb0YUZKxur3mrWjzlPfsv8P9W5/Ko2/EbL24LJGjHpen\nqd7lZ6Z1eGWWV6IvDA7g23g48Il4g08n15p5agCRmfjhYl71Ig26ateioDAr\nsFg1qz1jMOOSx4qV6onMJKoobOdnUW+wJm3Pp7S74XNVThN273XALOYaYjLj\niwNNh1m3TsWkUQsnmbP0XC6IeSiX+khaaockK1VxkH98qpzEweWmPJ4bA0VC\nAnET\r\n=nChH\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQC2Bw1HuNmIvWvaAIFM8toNzA0YalB0Ts0ewns3btlsZAIgBlghjPZVza0z4NAPcGr1oyTiFMvJhtSl7C2iI5DziVk="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.7.1-6-g0969004_1578996979132_0.6916063881800212"},"_hasShrinkwrap":false},"9.7.1-7-g2609a65":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.7.1-7-g2609a65","main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","license":"MIT","bin":{"restful-react":"dist/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","prepare":"tsdx build","version":"auto-changelog -p && git add CHANGELOG.md","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslib":"^1.10.0","tslint":"^5.20.1","typescript":"^3.7.4"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.7.1-7-g2609a65","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-+MJYpCdurFpS2vOJxyE+4uEDSwzUoRd6NxdrhURKsBAtHIR875RrIm0CECVWTYG3mlPvGCTOR/HlElkQGMEJXA==","shasum":"7919a2bae4d2af8d964786632a54bdd12d921496","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.7.1-7-g2609a65.tgz","fileCount":55,"unpackedSize":488758,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeHctRCRA9TVsSAnZWagAAymoP/3BnyGha8HjbvI0jz3gE\nC9fNiUQVQv3tzBkrNCWU8siBw1M9mXI5d4ZNQ5u3X9Hb2xawLw4S/yMeKjTT\nLkZ9VIlVS3Y+ODl5iiJppt3ZyG2geoh7QP/kMTr5jNPY3dXn719a/Gm8n5xz\n8vutKwg+VEkcQTinezmgyapx/veC3TeeLH3+hztbF80SoSRiHCHZE3M/Y4c9\nKPoIw/cCA8yk930yjA0alDQVqWqJpHFFxlHlBgG803gpCuYN+W1PdfKoepFo\nXEl7b8V6takA2h03tilNexOMXlIp88x41xgfy6U5PIGXJdAo1oFAm2XLYjm3\nGpng8icssQXPpDSDMnfJfeXYCtfG5Ivg3naNwYiZJlYmqcucr8fCsT9SNDRy\nS/b6h7MOZjH0JVeziHuf7EUp0TPCEe1TVJXgzBN6DjYqve7mT2EkhP+O0EYE\njMe9pLTkWMyl1ky6VSfTG2YKLjoU+CMxGqfbM8zAy2ysSN3cKhp7+OexBV4k\nyIu6N+2/SRRJMVY4gGpeGB+5yHL5uofHDBqXHtD5i7ZfbRQEU4kKqOlyCeC6\nBCfC/doS+m8/TvlqxXTZpF1+bvTvbKN9CJRlEjm6lCl/M5KPD532Tr08jHrH\nySr//sLR7jYRDQfBXAxMs6JfOkQH7jQU7CLXJRTGCbbwZNlu+ZkTwVcDGcst\nZbI7\r\n=nLAp\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCzlqPbZcaNfO78fZTQ+PQIrJTm4fOuPpStuFwN0yM+nQIhAKwmeKZEsI2LZPC1ouCpuwf6U5FMk9cAb2Oqcf74jSxG"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.7.1-7-g2609a65_1579010897423_0.11001843889088914"},"_hasShrinkwrap":false},"9.7.1-8-g1e2e40f":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.7.1-8-g1e2e40f","main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","license":"MIT","bin":{"restful-react":"dist/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","prepare":"tsdx build","version":"auto-changelog -p && git add CHANGELOG.md","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslib":"^1.10.0","tslint":"^5.20.1","typescript":"^3.7.4"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.7.1-8-g1e2e40f","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-emvNyEFV+w8vGwOcsJHEPPuXILcJcX27pfQktRTThrLNPv0N4GkzZgHUzanLd3z4Prln2hcURTFYp0s+z5GApg==","shasum":"0771dd0ba7e4d38617c760ddd20223e1d139ffb3","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.7.1-8-g1e2e40f.tgz","fileCount":55,"unpackedSize":489077,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeHc4kCRA9TVsSAnZWagAAW9kP/3SDIH3752RtxKK7AI8b\nhbtG2+1VXjDL9xcN7bUqChOcR2/I95oJujgSQSAI6yD3tLu9mPJGVCS7SirV\nKmyzP/tOzVyPixarP0IJ3q/mwybTiAxJ4QYUc18SIn4AdXmiCtJVBFJcEjAN\nJ/oR6UsEJph4GyUWaKydmv7IlUOu4oYz7vFfXmY/kGnJqEBAHKqM7iXsCuhu\nChsbtaUuIOGqXZo2njUh7IC7kDdsWhGFKSmLdpgnOW4yj40pAvT+RttMet3r\nSWU49fDxgr1ygkf3L5kJPVXMaUlEWZv0cBLR87VDUUbFjU7fEOHKO91L4/SU\nAvnuVWxvTI5qi+UEtLBUO1SOvmYdOP8ftuioUX+7BzwjwFw/NH2MX3BGbOB8\nSRAlRPVP7G6r+Cg//fmjd7uwob3QwH7Squ+HDvPnHJAdFHdJTV6UrOMQmqJo\nBZTKX7gN8LK7ne9dp4c/+sT7vEBqmfxl1EHQ352EVqiZlwCtQEbjxA2g8Xsv\njJIQF//f03oj0Msb58GTjXCqArcC9AoFn7qoZomaieKObVQ14ArN3w+8JDWG\nFL33aiSItYI/oRcQ1MIdebBX8f83NVdGWi4DHmWJZffUI1oevZwhsDGhgpB3\njANWJYM1VDPCqX0TW8XiUN7xnxSN3p1+whgEZgqzHRWhdr/abXjUNi00pecu\nLGG1\r\n=6JnF\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICQdPArfZp7uAK5R2IjDwZdDi0UWkB6086cP2CnSG/dbAiBxmetn4AHoKvsO/TcKbY1jnMa2AxZ/Ri02uZImipFomw=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.7.1-8-g1e2e40f_1579011620210_0.3371948663133151"},"_hasShrinkwrap":false},"9.8.0":{"name":"restful-react","description":"A declarative client from RESTful React Apps","version":"9.8.0","main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","license":"MIT","bin":{"restful-react":"dist/bin/restful-react.js"},"keywords":["rest","restful","react","react-component","fetch","data fetching"],"bugs":{"url":"https://twitter.com/tejaskumar_","email":"tejas@tejas.qa"},"author":{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},"contributors":[{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","prepare":"tsdx build","version":"auto-changelog -p && git add CHANGELOG.md","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslib":"^1.10.0","tslint":"^5.20.1","typescript":"^3.7.4"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","url":"^0.11.0","yamljs":"^0.3.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"122b4d469d670fcc6b39155a78f9d120da41d192","homepage":"https://github.com/contiamo/restful-react#readme","_id":"restful-react@9.8.0","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-pSDGVI29gQCGpJrfPEI0L9LRagM0EtRtcBa3wAmuVB8CPJXc28k1D0euqEsAVyshYXPPcNlpF6aIPo6a3eULCQ==","shasum":"48079db8666ed44582bc7de0cbd21d43c5db5735","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.8.0.tgz","fileCount":55,"unpackedSize":489592,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeHeYaCRA9TVsSAnZWagAAwQgP/1l6JRg24AwP+jaZmPgK\nyoHQfRWgi0RPXdg+qy7T7DTWKoDc2datuVUdGthirZq3rlU0lW/w3UYOl3n5\no7YGnMLCIESVT7vQjDjb6I03SsewzoEtfdLz34oc8JBTD+f2lG+tw+fT8kIh\nA6bYFPbkrD9AyZEA4jEzmDbySqqER04fVpnZIRQHrWcNiwjF05ILoK/lpK+c\nHQ73R+/oQxkHAJVo/UT8GhVPnhrI9eXimtZRdhVrr4syqan/8nnQkAQASeTC\n0T4XQHhPjhSYEhlsh8dHuLHRZu4drUmGtk3uaWM37UnsdjtK9RG5KDbw8kDm\n/o/T39dh2JJBTXODQk2iSkve0IrvEKgQLAUMezAgvvXt4o6mJ+2A0RCm+xqG\nbKUHUgYgS47/wFQj+sSGzC6MpKajVVw7Gq8uK3yg9FKtCw5KBPGozP8nim2k\n0tFtwV/K6GxwtXfmWSr66gpBxp0G4ZINoO+v9oUA8+Hs373q14mDRNNxC6qG\n6JasZcZVPTabBfOYwSOb8iZoY/NP0Ui9ho3aTzhPlzkrHpMKISw/++9dtgG/\nDAkk4JuGgk4ImpBsKX6GsxyU0y59jCL7bD9avYFCCucfHCM1yC/2Bbat/850\nAqK4tGZhkAxUZKJiWv5nogGaTdG1jBu332b2DG/Sz80hzgkh4gT76+6LY9i0\nK6ca\r\n=9sqW\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIERBHpejdPC4wipZKR2xRU7Cnaq7iyeG9e/N8Qlpy4SnAiAAq1oyBArpyR2dOrj5suJaLtGEXyQgbciC//lGUHFiXw=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.8.0_1579017753842_0.43429635686452994"},"_hasShrinkwrap":false},"9.9.0":{"name":"restful-react","version":"9.9.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","version":"auto-changelog -p && git add CHANGELOG.md","prepare":"npm run build","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslib":"^1.10.0","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"0c26873aaa50f1f660bebc77b8153c2c0d57d3be","_id":"restful-react@9.9.0","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-arMz5cQ3dEsJ9Orl+OJPDAj6s7WTywAw/q4eXdWNxgNezh778f7Um/uFh4N4XSt29p/mTzTgvidPz7j24GbwSQ==","shasum":"15d014d6a282287c7e536d8774bc2aad713765eb","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.9.0.tgz","fileCount":57,"unpackedSize":528060,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeKATbCRA9TVsSAnZWagAAHw8P/0WZyO9W/7tfruszrNww\nHfP8pHc542UbE8dp6NCj9Lii0GsIU+QQGj2mtXInN7ZpyqbQGqFS643H9C7N\n/Sc3dwYR+/DQQ7sOozHvMzf2XmbBnJqHkJjxLFwXcovks0b0PwDoB0RaNEYD\niGPlPr/S391G2vt+Ea5PBLOpsAY3qRfczSITm1DXAb4XSh2iBaA2C0kdxxlj\nqK+9/r45O0oVMNQMCJBLEN3aFEpi2ydXvTRJY/AL4z1HeN7RWTHXeZ8Uhhv0\n//89K/Y2xO5i14KO+0W2oDCnFQSc7l/3ukvOmWBz8pA4WMpHeRPVX3MceNxX\nzPy0e+V8HTHXpEh0zs/mgwLV5bri5G05DXluZKC5NUwhIUPmo/UjuCZKxQpK\nLDSvI2NO336oSHuT2nH85xYV73tKJUy+OTrGL8i/b6U2nUEGWIH4OfJFxGuP\n2K4Mu9ihnzWpYqB707MED6GYzikQJVbzWJjKQ6L5pS5MxI+FaKSAYrqfqXaJ\nm0PQ52bO9QopFlAzyyRBqCbjjGf/Tt78uttREETYGVrB0z5Ly3EbvcYiPleN\nRsU6Un1ThEcdwRRSoUZEeVyIL+kyb+LJoBwYHOREQosnS3nrAHQVfLvcBvYK\nTuTY4zoHnyE1fTU7Z699ulRkV39iMh4+XvChZTnJMFtIAnPX/VceIlH9Zh6a\n9rMF\r\n=mcKj\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCUoxv+nXZaO3rD4sCar2LpB04JcemL3klgX9ijdt1OjQIhALDYK0BeXm0RRPUPH4Lb5eQFJrG9uy0oR54mDG0v6ruW"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.9.0_1579680986899_0.3142195860522863"},"_hasShrinkwrap":false},"9.9.1":{"name":"restful-react","version":"9.9.1","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","version":"auto-changelog -p && git add CHANGELOG.md","prepare":"npm run build","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslib":"^1.10.0","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"1f9452bd166526369b9c9226979e016f02284dd3","_id":"restful-react@9.9.1","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-Pg2UwFrZPWHBBhEO0jAmloA7xPuJAHn60ia2ix3zrZOgbG6Y1OvzWF0Wb/5jUw/4V86PPv/6zVT4N2RbONw1Dg==","shasum":"69de73ee6d258ad27ba5493ae490ced6c09114de","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.9.1.tgz","fileCount":57,"unpackedSize":528339,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeKCyDCRA9TVsSAnZWagAAnVgP/32G8C8ZSOUgZS6+IAvA\nFtQY0v6Fb59aKyk/HMK9T7i09mrNojQYWPcpHkW4wsoFJPD8+kkUeIp/UOTj\nWQ920kTJ4zOLj1met4Unav/B/7IELnRzMkLEwpcXjL99h3yL5VG+OKABlEMx\n7FBZU2+GJ/DFH1CZArfRtDjqZQyNLORQ439vFXWAyscnake8bhQf4NgbxkEG\nb5vvCrueF73X/c4TUGRhg2ovzyNxyStlO26giQYntiCwQnBXK0uj3e537URZ\nX/us9i5jG4gScdjOqY1Q4eUowxKb0jAYfSIThO661kMs89+XJTzUOuA+p2uy\nM8M1KUMkbQ2t5ifYkzAjmaDRr0T9wF6VgFLqf1j7J7QCTlcsSr9v90zndmSR\ny5c1ladw7y+uuA+uokOwijuX/WRiIDuVz1NR7H4tHLPT18Q1pHQpjuBKAAEa\nEhV7iUwyUV3gEJub8LPkSJ2hMw+OXoNKuLGxyUnwV8uB4eNufx/jncby9r/a\nKmCDMYRnoXhp+kV1uuforQ0qkBp8A+0UIqn8iFrl2WsdIKGjBcReteKwWkM8\nr8oORMX/NpwpvneBuhuJxApAuR4b7kNfGw3T48xJCcxAh5EARKfK3LTmiAX9\nsFYpn2A5Zz4AcZSJKyheC3L2l9eiMT78cLTNNEyOU7RlDbT0j32Pe3tOtC+h\n1dPL\r\n=XEQi\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIG3fjIW0ZJ78jjzUHTVRzH5pbVL3ezZgcliFV6wSoFw1AiEAszSa+f9PSEB/oayJvboJ8NPIknHoWwfyaxm8sxy8Fo0="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.9.1_1579691138784_0.9177395527475634"},"_hasShrinkwrap":false},"9.9.1-custom-generator-preview":{"name":"restful-react","version":"9.9.1-custom-generator-preview","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","version":"auto-changelog -p && git add CHANGELOG.md","prepare":"npm run build","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslib":"^1.10.0","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"36a08c1b175616799d3b5e4b86e940052d019a03","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n[![Build Status](https://img.shields.io/travis/contiamo/restful-react.svg)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@9.9.1-custom-generator-preview","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-NX+5URiMKVm5MWCRSGVd0614eojidq18SOkZsSjBkXntDFJrJ4lNm9Phlcmx+VksTymKE/7y7U1xkgq95ZeNNw==","shasum":"b9c3063d7aaec95fcdc1962af9714dafc21d1c0e","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.9.1-custom-generator-preview.tgz","fileCount":57,"unpackedSize":529852,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeKWUACRA9TVsSAnZWagAA/OgP/Rjh9UdmQN3hCZU//UFm\ngf42N5mXCELSgdAN8xoqN6my1iq5fQG5QgRZVjbF/+Xg8r/SR4biBRugl2fi\nXZvO8Ke1SwKNOifLM5b/3ny9ISxDhxDOOFZ+NuyA/VnN4IpZiF5gSmv3H860\n8+cjvKYOWtippKU+QqbAedY7Jc0YMlScy3yUO7By1FPTlic8ixUP374HdO7y\nucTXZrqRCKRmXsBsX26zPW2/p7j9TdalS2qIF0JYA1L24lFtxYegfC8sWMmk\nckdEA1/ewFhq3zyGW7ZmoZbj3y5UTyKoHfkFXxkJF+i/zvhjBwFn6I1r4NHE\nCgGBv0se4AdfwY9+R7YW+62S06OGkLJ7AJ+3/YoDyI5acR0XDigT+6w67RxT\nm8dZWocdbV1Kx6M4cLlnfDWRA+ayP5SaWMhqu+SN/OlHEOq8UPzqPe00/Mis\nar3jWDa7hcinBaK5Y7ua5Vs7kwX3RRJe4uxbEVDWQjDPN9tKH89HxSDf+MTM\nwDlIF+yTOyoQJtT7y8ImkhiUlZ1fryJE6gy1vQSYAb4O/vXzFcicewVwJMtv\nwSGJwMDeRPM8AkZl49qrQ58lw1YQra97h31eEVsmAtyauPLGGg+8ssPpYkQK\nY1XLNslysp2/Jch32nvU0XMOODkNyKiTBxMGIn6TbNO4FFrg+fTo53++sF69\n2izr\r\n=WMR2\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICjqKtXT9TF7iTwGZI0RcPirywxeqiC2t4KwGjtbCONuAiEAwy+UDTkOJszLQE/i6JAsyfXwvd5dmNLv3Wzrczd0H/M="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.9.1-custom-generator-preview_1579771135639_0.13927176645917072"},"_hasShrinkwrap":false},"9.9.1-custom-generator-preview-2":{"name":"restful-react","version":"9.9.1-custom-generator-preview-2","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","version":"auto-changelog -p && git add CHANGELOG.md","prepare":"npm run build","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslib":"^1.10.0","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"ec9cc4adecee3f46ee3836dcaa49a084080918da","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n[![Build Status](https://img.shields.io/travis/contiamo/restful-react.svg)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@9.9.1-custom-generator-preview-2","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-z6quIDWNhcVjNjRKzFXv5xJaQdwhwjLeJqrs2yk6yHqtLHwLPKBIQGLv2G7obqceS+jKCSCyOnCKLw78J8MaNg==","shasum":"a139609fd85e9c551b0abfcec6573ea0ee413633","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.9.1-custom-generator-preview-2.tgz","fileCount":57,"unpackedSize":530537,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeKsh4CRA9TVsSAnZWagAAKFwP/1GJ9m0qBG4NwyLaf8Vs\nIvPiYoMcPg0c+WIvykoB4Ab/5PD7Yj8TDF+fwBj/Md9cHCBPuhOYGpvz+ABU\nssYX2gf4a/7T8/ufSQoMAxPuYUi4Ifd2n4+OMYiJkU+qY58YRYReybvPNLu7\ns4tlgSuNwyVHp+Y0vl8hEs9+x4rxmLI0BPLFg7RSgZ4Cmxs86KfRO42TkdeA\nRczPdczf4h43LXh979weyWMpdRHV5ZdvJh0svRTwHN/gixb7zXb4Z35RTWY2\nsu/T15VJryQFXF3R/VW8rLU3A6M0BnB5f+PWdq3GQa81YkVgwSXXJNJXvenb\ngGqzb23RS7o+lz7fuYzBxMYPyPvF6Sq5ZDeWMfQFauqE+ch4tfIjT81mQ5FW\nIIwSGcQQVc3ycMLIlBZUJM48GFR+i4+MZy5NUFLmg37jKFGRQ9fEMFE4T+Q9\n+Ra0WRbUzEJU2RB+BzIJNVYyk7vs13iUCbcE+DogoSa316SH7yn1G+BDFOzr\nJ+oqePjZ6A8EGJcUFusMIheyhGHsx0RZQbxxc6Xschrl/1Q5tZ6bVWE62jCm\nPfPOSsakdksykd1h+mXiehwuzRG/wBbhOKykjUiAe+peRM8JLPkNOgIjZ+bn\ntjs8t3DUVkWoi1r0/IOkqBTdqgWJJHRQq4dQLFRSFNdVnq2Nlz3yKIhNX5lp\nXIfM\r\n=WVHq\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICppv66yH7lfshobq9pK++OpNH+skB58DGDTg832Nn39AiBoSb4CgbzWHpy4osFHBHGDg3Qg15qIvBDJBFn6m3uTJg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.9.1-custom-generator-preview-2_1579862135670_0.23495640354004288"},"_hasShrinkwrap":false},"9.9.1-custom-generator-preview-3":{"name":"restful-react","version":"9.9.1-custom-generator-preview-3","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","version":"auto-changelog -p && git add CHANGELOG.md","prepare":"npm run build","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslib":"^1.10.0","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"ec9cc4adecee3f46ee3836dcaa49a084080918da","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n[![Build Status](https://img.shields.io/travis/contiamo/restful-react.svg)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@9.9.1-custom-generator-preview-3","_npmVersion":"6.4.1","_nodeVersion":"10.15.2","_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"dist":{"integrity":"sha512-dlWMel90tkuclCapIpTxYMQQR9W/JUNHUjllsbtD2Lm6YSoLCaBnQJAkGZAyilfhJgdAXJuKJFCcb2+ZqkGTYw==","shasum":"3dd54212563823cd7d20e92f9eaed561add433d6","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.9.1-custom-generator-preview-3.tgz","fileCount":57,"unpackedSize":530690,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeKsm/CRA9TVsSAnZWagAAbJIP/0ZpIac8bEVPwQp8GkAB\nMm3WOCqO9sgcT0FPwIJxo9JRGhLkOgl20XBB9+WZkVRDztdhMWr+TDbKMIuT\n50I5iwWGTE+LW71vshpkeZ1HsP7oNWDHrHDBTtTVvnFXhA7bnh8Adip+ZTvR\nvco/2FoJ5k5sA+at/lnxeu18Pl0/wDDRA6pz+TVPXeLWTpmB0ur98SowTEoP\nW/L8dUnnppZB4NKjsssIiqJqGMBlW+a34aSqJ9eA3jXoJmvN7Yzh0GU3f6be\nCYf8z4xuhFRtdZ2SjZnOrAy3YLt7HLw/7AhUja90NTtAU/B2836u6XGSLwFD\nQ41BmAmpqwWadW9WHllS95UEZgBiLOqbriM3QeyehROdVO2Sc0WnbFzJ9hnk\nK+ujEfyLrZNE0VtSbWOl7wx9Q+4pz/rXcQjskYCSx2WsrX2J5yHRWWJVZbX6\nNv7PqsQRpVe0BgZvUb9OSeGvd16xDlpLvT4iQEpOqw/R9DQbuLVOuYArF7oB\nQn6IlStq1+qd+XyjsyQXuhQRNNOZ2u6Q22yNG4HZYP/CLx0DmMIe1rOP5Tnf\nV8T7MV6tAiBE+BVaRpninFqWmTXfdPQhUw0GGfbNHMRSWJVLT9cIkTNTohMm\nvi9TTKTDTWM8LI61Gyt3WAWljSJPvLjKQwoNWjuRIrdwtLJVnXOroSOyydhb\nDu+W\r\n=+eUA\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIDviVLc9C5CJK6TrT58DJ3C2jsU9hT6KAY7gayF4eO21AiBeTRzqQHaUYMgX6RMgDxfaZqATxIF1wGw0zW7P7VVrZA=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.9.1-custom-generator-preview-3_1579862462545_0.7162261408489603"},"_hasShrinkwrap":false},"9.10.0":{"name":"restful-react","version":"9.10.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","version":"auto-changelog -p && git add CHANGELOG.md","prepare":"npm run build","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslib":"^1.10.0","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"48447507921c60590b30553c740e49cdd64cbfb1","_id":"restful-react@9.10.0","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-dWgndPHMH+asj0U6hRFHRyuk6su0SNXX8jru5xAcTWksZJAqIJaf9rFdBAVh4qMCD7pUEu8KVHXpRvpb4mxmDQ==","shasum":"422b3349183e000f66319ef79c2971c591fc4b4d","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.10.0.tgz","fileCount":57,"unpackedSize":532078,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeMEhUCRA9TVsSAnZWagAAmfYP/1ruihocp3j/G1sSXNr1\nZyHNhRszhvDu9uwwMzNBdS7ltKtAU9Vd3TNRFppda+aVnPvRAqZdijjpVJ7y\n89E+4GWb7cJmTxsXAASPLX9JJpq9NzgPjtWT2YbWEyYYK/MIymxAJ/J8WaX7\n9ng1ijFxDjzPQ7i5QzXjMXVvlj2ODWcYLvt13FWGwpwvsuxpLCvtdXNRduJS\nd6JPmnVD352aUTNwvslyngBIIe5Xz8lPyrwgPNXuAmO22nD9/uV4JC2SyHDy\nrdENWVdOAxlXfNYT+VzEklpIPrhx5fs9qLJX9Sd1Lgfc/XN9UMyS5MY9Gk7M\nYzvLjGlCXKRi5n0uYWGfaVLrsKWVrgB71zXd6UTLFe4Nf7eEWW6/WHNEcDQf\nLRNt+DPSvZ1m3AcDoV71wnNRl1LQbP25QJ1Kx4lN5yn1t8N65Z9nb9g/bV9e\n//bU92fw49OHQyvKZwWuCwwCqvlk/4lFtSz09luoqmNr3/+7udJxjuoGSial\n/0xKQeWlgHw8bWKJerxbuKXP8ceoY/kquRWkHdtDnqdXlXz2n7Am2Fo5MEqf\nhAozdVF2qDCeSE5gbMpF/CUhDm0iaBgMktBauCJul6SAJowWedxUPvQmF2/Z\n5im/4FN8nD1rtvcipU678o92XBFIobeBddxgW/HgFkf2aqzTgZcew1hcux2+\nwM6N\r\n=eEHf\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDxwG0UJzLE3d80mPYIuhWCEB9Qk3L/3J/7wqt7H10zrQIhAKjrav/tCjP6k/RdCYSUPbNJDJCcosf6+JDHaTGceRqG"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.10.0_1580222542713_0.05911620938184048"},"_hasShrinkwrap":false},"9.10.0-1-g61d0088":{"name":"restful-react","version":"9.10.0-1-g61d0088","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","version":"auto-changelog -p && git add CHANGELOG.md","prepare":"npm run build","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n[![Build Status](https://img.shields.io/travis/contiamo/restful-react.svg)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n    componentName: string;\n    verb: string;\n    route: string;\n    description: string;\n    genericsTypes: string;\n    operation: OperationObject;\n    paramsInPath: string[];\n    paramsTypes: string;\n  }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"61d00883c324569b73bfd8c47da27933c8eeeae2","_id":"restful-react@9.10.0-1-g61d0088","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-otK/6jlWsm5fJKKtz8Wq6hw+San1t/NImEPwgP5R8dmspshEwKLZ8Ok0nqy4SA4bBD27e1oTdWVuJ5wcR1nbvg==","shasum":"ddddbc2997d896c40a3ccd52bc30cc4e8e5ad984","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.10.0-1-g61d0088.tgz","fileCount":57,"unpackedSize":532065,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeOEm1CRA9TVsSAnZWagAAxMYQAIQ+syVocysajxMXEvCE\nvyZNI4oYSMM3zSqxlnfzz9Nu9URaLjMuVgY7vhP4DeBdoeh3+oVfC3OSnlxk\nPlIYpDHkQQoX6MJ7axOn9diMn3Hcd0PH4tUhI2CQIDR/juhUYWsL5uwuwRfj\nUIzbesZP/AyW/R/+i6uAsa8lJeXow54Fon1vB2Scw5Wbum9/QLJonoEED2l9\nl2LxTW4Pp46KPObZp3rwVW9uqjUW/lBSH0xZtMFZ6+jFuMqemF9wW29tX7tX\nlEGOtGBOawr+hJo1XpuZ5SNxdexaHmDY8Fl+QOzfpsiGeSV5gTe2XwHE4zeA\nVWcFJm1y25ySdDaPsf8bN8bg5hUiCPvDJpd9Uo/FjodEa8rUfYd5xPyTfQMW\nKHcfT9gqDx9Jfog3TDwON9o5EqPntqwLkwX+6jBFeDjUP80LRxBLGJYOhPBO\nKafCv+YOhqAUoZDQyHTkVFQfOqxJJzY4yl7ZZuRMbC+4S0f/588P1Y0FF1km\n2zGpJ0F8yrIcDE+OARe5YtPmtKRjrr5uEKgpIdvDI4e6kwZkGd63uO6JNAVk\ndPbICJCOGUu5nriE8ksKJ371kr7kxUSljepARP3p3FFR36J8p/NKdt+PikB9\nURZy3jLMq5dutrleGDP2RxeNx8t8LNXHFtt2xdEzA569KqC5T+PWIbq9OgV5\nCst0\r\n=qkkR\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIFx38ebCrGuqH6iivK7JLOBo/D82rYvHh1A5L/NwPhb4AiBl+xJQgQAAdFOSoqEUdfb0QxN/WTImWv+yOkOVqmrvpg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.10.0-1-g61d0088_1580747189105_0.9753986584847192"},"_hasShrinkwrap":false},"9.10.0-1-geb2096f":{"name":"restful-react","version":"9.10.0-1-geb2096f","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","version":"auto-changelog -p && git add CHANGELOG.md","prepare":"npm run build","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n[![Build Status](https://img.shields.io/travis/contiamo/restful-react.svg)](https://travis-ci.org/contiamo/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n    componentName: string;\n    verb: string;\n    route: string;\n    description: string;\n    genericsTypes: string;\n    operation: OperationObject;\n    paramsInPath: string[];\n    paramsTypes: string;\n  }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"eb2096f6d02ffb14b9cd553c2998f847e4dead33","_id":"restful-react@9.10.0-1-geb2096f","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-nxp4te8Bmu41ol96jJtkuXgIvOzsshScaSKpljM7vkYtgjHo/CUUPLuKcOPHMxkBOnAJqF3jLugDXyl4xLjIGA==","shasum":"6a044da8c1eb56840d62a4671a838487a563239e","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.10.0-1-geb2096f.tgz","fileCount":57,"unpackedSize":532089,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeOEqpCRA9TVsSAnZWagAAegcP/2xqxV24j3me6WSoqdqx\nfusqNOM/cg7uYPaYQVAvyDTx9U1oGhF4Z1innLunGdbpqg4IN3tcSEoY1YBh\n81SbAtC0ofafeQ5zpOtFIrFTFeldqghhIBete4WON0xV2mhn14bJ1MZiR5w1\nc+GX52zlkQyFPkue8kMhb8FFxHtcB+rJ9tp7AKuznEb+aM4QPLkYvOlQWF5K\n8rEHt6mZh5x//qhbOBC3Omx31G75m4OXdrNCWmdHhc3r3ib5+qv1A7vsYLQc\nu4UdcTHhIKaNvNTa7v0g9l6bKlo3VHY78HD3cI5g3kTp+rWigCusNX9DNk1g\nzoQQzhDLNqYNwc8VWh2xSs1+mHxb6SDvuv2WDjol5IuTv4DvYxfXziFBKKjG\n0xQ9FIIqvpFHzSSqwiFjK1vl+ey0WSb0KuAVUA6oG68q/3qWzB6Qg81qGqaE\nfeGHesIOO6r7yhAvGuWOdLxSkQlf/LKXi77jDDj0VT+QExcMrIhqpHOaOJf+\nn1dZyHAM3dTINYFSs0AJpaY3pvtFelPHmMCljQWG0K8iihQQVTWduemBV+bd\nDrOjsZ3j8iSenrr+YZAaWeqyn1YatiuehZwgW2C4Q7MGAeB6dP9cTRabIYMf\n89i8JKEFWpNipLdYNUh5W+iJYXUGek6WQsuCfKKozzi22ulcIs02ed4YonSl\nVEFY\r\n=gYJi\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIGC+CG/Ik25F8ux6oD0u/C+84r+nWARqaE01viVhzTWpAiEAmVH0cdaL9ZIkmyHTuRXp3+0d+0CMjNSVgLChVIUcUZA="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.10.0-1-geb2096f_1580747433218_0.10659133652559771"},"_hasShrinkwrap":false},"9.10.1":{"name":"restful-react","version":"9.10.1","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","version":"auto-changelog -p && git add CHANGELOG.md","prepare":"npm run build","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"347a924594773d5026ff58d667f5685d86c76413","_id":"restful-react@9.10.1","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-wRtdf4vFhrJzqNGZehKDDSr+ib716eEG0WBp9ZjHCckNf5gGe+huRLvmmUXL1l98w/VNgYas5rrGDNzR0jykzg==","shasum":"bc2128bd3a3bf5a68f1f86f2143b512ffc565e24","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.10.1.tgz","fileCount":57,"unpackedSize":532307,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeOEteCRA9TVsSAnZWagAAgZEQAIo9nbhPL26KHOjeRkIG\nDMYbOFvw3U2BzoKRN1TdbOLO4qzDhwbrax4SJK5xDHtCpGBahU8xB9jazpp3\nCKVfIqNriRNKHDTjbiWaDe52gfzv82QtlL5JSJIjZpVRjanahHFhGcNtprCz\nAjKvO0KuOa7S0SEpL8fKKzRm4UiZn1qAkr4VXKsFdlC3dCApdTiTFyUMe9B6\nlZBkCzFDZlZlSP2TnNWTUudI8gxstxPYydUrQWRidX6RnAbLiU/JBmuRvJNK\n05EyJ7QJXs1bVwqTu3K+PfVPtCutYn/1eh8bgLDOHG5Dsk1HSxGwyAi4O1YG\nABX0C4c/umjUBVYuNKs1b3MrVTHZerBr+CeF4xBxmoVxh627uyqfRqvpfVFo\n3LtRDXw3C02u9Hv349Nrtf8gadS0D1xdrAMx8isjGPNd/E6UHXZgNTVuYunf\n975eUvKHdvW2Nq7KiKf3Tz0oRcrXLyVR/C6UtAo6Pb9URRbuf14UJbPBmbBJ\nc0OIgX481iBukWYX/cHYlnZ579ZFHcIC+icOL1usMGBkzd3xkAm0jgtilkJy\nEDTnCHrzladFU7cnJZqljTtYYGYfmvXkM46L5rE0mJYLkJbe4jVRZ3p16Qw8\nFBMnZFhFp1Ftv55bI6dbKvrD16ZlCKC9utnP+AUASMJZ0yOAKZ4bsvDbC+JN\nru8Z\r\n=6fES\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIGYmG8nCv4LyXauqinV2nr/PvWIiKxGriOmSCDE1sKO9AiA0kxIeip/cIDTFqaeCgs9+fpJGY4acbTbG1287U/oE0Q=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.10.1_1580747614488_0.1610555116430188"},"_hasShrinkwrap":false},"9.11.0":{"name":"restful-react","version":"9.11.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","version":"auto-changelog -p && git add CHANGELOG.md","prepare":"npm run build","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"c7c4c942d39b9ec3375a5d54b348e03447dbc40a","_id":"restful-react@9.11.0","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-R+AyI3ljDGP0L9HOpmE1oBCgmnwabvQ+dauDQjnv0c45Zc6L05aiwhChN2O0+3yuqmiRFUHBQuXz1ZoSbS838w==","shasum":"7a30dc222d8559e8ccb355869979f702545741e2","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.11.0.tgz","fileCount":57,"unpackedSize":533407,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeOVHBCRA9TVsSAnZWagAAp7YP/1TKITFJiP6Z++9aVl/S\nP8HmPCP0nrPaL15oISFGBlrqAmF25ebMSjrq8yo8K/D9q+eE+k3X8mbgrccx\nJropp2r9edFyzEEQzECWl/FvyJwcERdMLvipDA2KbOv8jq6XqaBd+YXibAnP\n9ucOadm9/wjH8skjuSMh4IsFP8tGQ3Ix3hFg9NmpAU6gjeg40gnbldSwrgFx\nk9gXEXc6Nwef7EYZGPrqTTELt3PbqS17m+AFYAjsRGyTIbnWsz5ukEi1qlX9\nAtdN7HmWaUOEjyRyqNPUi9wCNwp6jm0Fnp8f/wdx1B4Ba5CpLpCfroPDby+z\nH2/Mzvd9GB+Yjq6xNabSRjnZa5NHW0JSEKszQeGS1xMvxo0o2t3a28bets8I\nv7z5b2pVrtowTN8ncdnUVbZ9sDPKTxLK8nD95neewJp4OacXielP1JvwKazK\nOrFMLX4yoxEfv3BbX3qGgI1ubvfPiNXv4WSvpJd4VjvRTgslxfiqv9TpCdSm\nJUkiMc+uRpA9jnIAXVp1XGBD458pLJiNKgZXjUFjNBZD07EWl7qwBdrv/s2Q\nNgPGcMhPDpajWl/5WymP2yIMXWq749y8i8TXyTT8TgB9SYndcm05Na1hE6m5\neqFvgc6XTIsYFashF5p3fqI7Y178CQoY3xWl9ptK4aYr7LLWi3WaNucg7eel\nkSti\r\n=Sj7a\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDPP5tDW8G3wlKHwOQvdiodi62BfbuuPFcNeDsEFKiAbgIgGx08/6L0QGgGH+VBuNEKk2bK7U4MTZqYJzf2iKeibzE="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.11.0_1580814784692_0.014995159693490967"},"_hasShrinkwrap":false},"9.11.1":{"name":"restful-react","version":"9.11.1","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","version":"auto-changelog -p && git add CHANGELOG.md","prepare":"npm run build","ci":"[ ! -z $DANGER_GITHUB_API_TOKEN ] && yarn danger ci || echo \"Skipping Danger for External Contributor\"","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","danger":"^9.2.10","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"f8b25ec056fe6b9bee919fbc62453c57d8464d31","_id":"restful-react@9.11.1","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-IQbX4tgkjO2M2J6FcYFRsWUtAH6Pm0B4pC5yeB/a1t+24JX3IsGzz7jPO6UarQpU0veG38t7NymhptPCYupmSw==","shasum":"2059c4c170225e968e1810ef238fe181c7f54d70","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.11.1.tgz","fileCount":57,"unpackedSize":533814,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeQmn7CRA9TVsSAnZWagAAfsQP/1CTn0sTrVw795BO7jbQ\nC5hSGm0O00DQB5lPCNH/MO+9/Vx/5X59VH1EvkzP6L3y8yzGiyDpxcnz9nmh\nAZiEdETV7XuS+3GyPCyhbIq96NR8n1o6woQoWZEXeQNEqNjUugOjvD7M6GX/\n+BgyUIGnaf7FZ6SS2kZcqy1ns10ppHBFLa0xwgeALh1cVxvteDbRVJMiHSp7\njAIRHyTy3gW+VBZ42H3vqatGQHeMQ2BbTK1To0Gkcn4wjQDV0MBFa08v77Uq\nwtbLv66aagk/iQ1sgOIyy6YZAuDR2YhKgVhmqT9/3IrT1TKghxi1hlolqwqZ\nPUNtw1j+Duv/eVcza/tDEEA9L5lcVWVgV7dcfXwYyrvahFW+0tYN5mzCy2WP\na5z1SsxSqR/c2WlXK4wdVvDhS1O5/K38iL3aGuQlF2q2v+7SDKJYpbhEdJsb\nOX6UaTYK5agZNDXzPQ+BGhBN+TnIRIQ/+LVO/R2kJEflQn798Kg1MOdgRkMF\nqQLzD3QpBlx7tVU8+pv5uVzwr8hyXqjmJXV/vuea1oAkvinExdYkq9EcYSp2\nli5Gqpn+e6K2eeisXWEi/IrXfky4svijQYSTqKzIHM3Awhyw49Vmb3NmwMYI\nNL6hkHUOWpWzqW//XM0pnpy7ypDTE9GENbaGXNEzD4cR0rlTn4iaIuLYagSW\nzMbk\r\n=0tkl\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDL1KElwCcfIqGHq4rG9Z6AN1R2eKGaYkCk9N8BPxsneAIgfsg8mOnYQtBPbVYhoOQTFPh2uiTcUeuMM2IBuWSTIsM="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.11.1_1581410810988_0.8930820821777079"},"_hasShrinkwrap":false},"9.11.1-without-cli":{"name":"restful-react","version":"9.11.1-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"eed1135cd3fbc3aed29ee601ad8f57305548f0a1","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@9.11.1-without-cli","_nodeVersion":"12.16.0","_npmVersion":"6.13.4","dist":{"integrity":"sha512-QB0r7oi8q1wyi+iW6oWguV6Anye6eT88iR8sfNlhyiLbc74tH3WrykDa9EqoWKp7ndu/I0AMytz4L7C42ZgtyQ==","shasum":"c1e02c996fc38fbfed1223e227c3450e1c4a91e0","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.11.1-without-cli.tgz","fileCount":45,"unpackedSize":483113,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeSoL5CRA9TVsSAnZWagAAxq4P/1xeOSiPk+eqd4to45S7\nlNEmRymbyQM+dZhwytfs8tuw0yU7edYXgrHmIkpKuuhRaW6qHf+emk8ceP0j\nXAnIvyEUajMlnbv6QGZJmvv53dcFBNB0yhO4uGcgKGxFMOFCdwqMeP3eugWG\nJfHTzEEFb/JTf7YYvKs0Id6AXAruzay3f5aHnHZmNsfALE4Z/mZ3a9QLjNum\nVsa1exxcOZuS+wDg8J56rEKiLnqD+mDAjNmi8ILipA2mOp4JdP4o5i7QV74p\nyb9bMB7/QfdmgA6+8WLWZgOf4LEt7Zzp0oBTpo9Tt1saGDSG8r7nW3oNimvF\nCnWcLpk+7OXLHMUFTSAk8RumS5ulWKPgV7HqTKLbDIGUv0KdiUja3maKe6JS\nD6bVEL6B6AsH7rq6l4nz4cEeYV2gjEIMioI3ut5mLdx0JFu5FQi/h1AtQnAD\nxkOds76rwDqiJVQI90UX/T462gfT1ZPHHsnS8sRsTP/lvUUxGGvo1Bu1gCp7\nMvILdHW5L6UA/IVt+dcvtJe3ZcmQH89HkF3/v0Ach1sa+boxM+Np6Hnt+kC4\n9yht/x4OffvyI9wHyh+iEnA7aJYF1yDXhhs/XIkVC0LqB3vXNh1xJuaowkEk\n/n2B8qZTQnC5fU8/JyQAkSKLpimTHbD57WEE5nmD4P9AtgOwX4VhQGHSTlic\nbgFm\r\n=VTuH\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDxQEElvheIlA2Yl/tpnME1CwC+w25Kr/bUeU68lTUC9wIhANXzFDxEcwsuh1mBdGncVPY1ZBGMy80zVr/XRRM+CT5g"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.11.1-without-cli_1581941496958_0.027632044325038407"},"_hasShrinkwrap":false},"9.12.0":{"name":"restful-react","version":"9.12.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"c3cc3173adac24a5df3e17393d2e55fe5ec8cf1a","_id":"restful-react@9.12.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-5W5Vc3WAniwnqwWTUlTSM2H89g+VZN2rfzycutuAyIlG2Cyv5PqkO3SKUSYdfqNtaTcZiE0FE5FJ8kwKs1pARA==","shasum":"ff5be6788c954469a5334f3b06dc719bef3fce7b","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.12.0.tgz","fileCount":55,"unpackedSize":536221,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeZfhhCRA9TVsSAnZWagAAMZEP/2epqMHBP7lNPt4ogmJH\nchtT7IcGfZRORJ/KRsSTgjQ6XbgS/tMQqEAsVo3CQhUMdp1fHjasn2ZeoyNJ\n9ooR8z+LT+eJYN0QLPmLKNpj4hxm3RwBXOSohECFd2EFGDkprRlZ1kieugps\n+u9OxB5bIjYMMEXNFFugU7OijfaMc2TysbghAwxqaC5mu1ai9R81jTfi7lq+\nBn955P74iyenphRQW0f23W/ExwRfl5wJzpPt4jWdlBGhsn7glUc6Be8pK5SS\nhlDIKOuEymlt2mHQGatRYRUg5e1dEyZmqyQ9J4OD4hRVg42UUpOVaqufjHd+\nbX4KViN0lLE2Zw2oQMxemESZ03BV6LKhMZuuBEm0MSVUrRXf+pCRqbM3/4TG\nSJH2XEhDF5f42tknVd1puaD+g6k5vkb5D6DaZSu3cBltFGIS7ErywYzDHwFL\nMIQmxIPKoEA8bHH7kHalP8eZ4epBgCfzLGhXIKYqst2PuNEqxa8tpV7qunix\n3gwTz4q6A/UoduX04ZhnP+pXnh0+ojrbBQ6TCH1JDVzmYQrKPlAWwUq8oQLz\nAZzvSwBxKtPAyL/C1eaGl0fA86YJHxsHV2LKcxaEOO4QHT2Ac92RJIfV/JAG\nS6QdkATDwKyZg2OCeo/+O4KpDG7IMttxRBVtu6HoEI0olpgpQQzPAG4T2JPq\nXbyE\r\n=Vntn\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQChMQDQngOz9rUL2lPJUQ6rqaEc8j7t80bSpBF1VAC7ZAIgGwS6QwxBaYO83cjyutJsKqgWq0RDo23Vh37/W42p47A="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.12.0_1583741025285_0.2149395225574533"},"_hasShrinkwrap":false},"9.12.0-without-cli":{"name":"restful-react","version":"9.12.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"c3cc3173adac24a5df3e17393d2e55fe5ec8cf1a","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@9.12.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-nI8z9+CqnuAetX71ldb6P3KQD2LeDXwOrPQITP0e3JDkQbQQaspoQNYvPOp8c6+KgxJbzRioSsMSKYJUlt7gDw==","shasum":"6fb4a81c9d3b559abfa3060ecb263730553c30e8","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.12.0-without-cli.tgz","fileCount":45,"unpackedSize":486201,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeZfhyCRA9TVsSAnZWagAAnqYQAKEMdkwhNi0rtyhbRSh/\n+8Eu7hMm4icDcAefSJiINX2vnRhMBISZwwpEjbpCJx/Cd02n4fQrNEd60jLU\nq4J67tYoSaRx03YnlboJV2pHskrNxhYAnrfF9iVtzgnAjBhK/hDPVnEzfHF0\nvl4877MEPrHB1JjDVTr8UdfMnXhOgeMUu9fXtD//vSB1J2SDTnZ0heb+40pu\nCChOM36SBcS1E+RRi5dx1J29whFvXtAZRIJzgkBke6yaajS+ggUJw9p2Bb+4\nEUn/0O3TMinkEb5SZwXWgHEZkoRNI/zYslZZ2ZyubanQk+0+Uw4MuyWVj9km\nE2obdLEWGrVehaWOKKPRQRYA3RX09hG26V4nwrq+Yr38XgKV8eaAHNaiTh4v\ntM5nS4fkM/elpR4LoeTyjHC1hXQ7CjoB5SOstpWjjd1mlT8s5IzbpQVzzXpj\nrvWGm+RdwC/kH7DLFLwT8RL37dBsSFVYX8LhBqP3jJI5QYZBL3zyOL6y+nb/\n1SyPDMn0bESgfsVWuFHsnZe5koHnzanYIa1uoEdySuODLcobnUqFPsytjj/q\n+LCJa1hhkd0N0ESaUtlT2fO3d6eERuZOu4fhr77oq52paazjIpX+ly5bhPue\nq67dGRO4E/AA7LT5HqDeYORHFGgq4S9or+BUDHcDcKsxbMfKRDu8dvwrQQxW\n8piK\r\n=Giao\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIDEpKMCEdgBa4b6WgEr8QTG4Zlab03IGT2chv4xYeY/BAiAyl3Ur1HqHC0d9KGzXsHHT8Pr3Kvduaegr8VCf5jda4g=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.12.0-without-cli_1583741041453_0.33683257802275457"},"_hasShrinkwrap":false},"9.12.1":{"name":"restful-react","version":"9.12.1","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"d1ff517bc75baf3d575269de7ebab64d9eab3c33","_id":"restful-react@9.12.1","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-xdIZtFG6AyY1G92VA2ad+k8gIdbUR/JHzS0X4VxSueDQPzd8cG+h8gXxZ4NZho0953tlBM13YZYmEzYU8fFbxg==","shasum":"ab028d7368c1705697c254ab86da3667c760412b","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.12.1.tgz","fileCount":57,"unpackedSize":539192,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeaiHXCRA9TVsSAnZWagAApbcP/19DG2vsgqEBZtQpz53e\nlIKrnhrmbOcB0LCGwcKS6Y88LtVAK6VVnYlXkq+e2VOnucJ6E5/84INbzXa6\nVqA5iOPA1XDzm0vUxeDsCJaR5b4Ck/gpQ1+14PTs6sQKOQTz3O34W6TTZxPf\nQWcvWmT2MshYmm3OKtH3sWCgkruP4H+QiwqnNRN2926ONzkArZprArrHA7mD\neQVtDofUPDXeMseGmQye34DwxIsCEcVv9fr6J0BvmKZjSArZwO+z+z6lZkgO\nkGnwjZforZwCuzEY4l+jgZUfQnR3z99+4ahQx8wsqLN692alx8Ttps9OotCX\nxBWBZKM/4Pyc7IGKkJhiWPuu83z82YHX0gi6/yn2n2EnDXKGGD0VgXrbQbM5\ngUD4Gam5hNPKEsL8MWdYVvQbXZEuSkUvPi7QevovVqPcGReQrVcoKA2r7GVm\nLJF309PejPBzTq7F4AmHN3XwbIs6DJ87wef5tH6zAsn1Fnswm/pOb1HpJbn3\nuib6xcTBcMtJEiz5v/kX/qIIRtFZk4Y1uCxUBOamdtDxQFnCBrodDEK9JJWH\nOhlmOLoT+3UeEPE2+SPriQ4H+WlN5rtvC7qZGR4comUgSQMsOnz8OotVB3NE\nMz0sddGs6GXg/XbxxSy+dAWgcEdANyydDVmZsKv/waC9heSeYXWRUaqm/QCa\nW4kJ\r\n=/uCT\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDiUVoB1uthgsaUleZ05Ji01sCvFD/AIq12ylrLxwq76wIhAICJKOSwhnBZ6Wb4niavGkySf+NUQehNB5M1bIXnyinf"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.12.1_1584013782520_0.8839501115296575"},"_hasShrinkwrap":false},"9.12.1-without-cli":{"name":"restful-react","version":"9.12.1-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"d1ff517bc75baf3d575269de7ebab64d9eab3c33","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@9.12.1-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-OunCSKnJyZITkttipYmMdv3/BKpqyD/Yu1kPMNtSF82OpO8S6sMVneOYLb35uxC8cR0jM/6IVs7ZeX0rMUQoqQ==","shasum":"e4eecf560940f1d852c784d4bd6213ed65a65cca","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-9.12.1-without-cli.tgz","fileCount":47,"unpackedSize":489172,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeaiHlCRA9TVsSAnZWagAAmlAP/1JYBuZQ8WcHrR6RTXQW\nOYGrGkkvl1EyJeWfIYrCw4MNj3EoNAqXUyyVWr8oiGksdd13jFqH5FGEoz4C\ncB7mEwN31CWzgFUWhiH+GVaufBGMb1hBOE9A7j99mcnxbF2Cy4sMBWdkPXlk\n0nGBtuXBJ7M71Pav1c5/dQhM4S5MmwxaFBqZJFNQ1ITRTU235DgYukP2VH5u\nFrOZvv1VpnkQ13OvUeBqcj+mlywx+l6smFprVqWSDClVxmuwHFakPsdcQra7\n+b5M7DWrsK2eUtUayMv246ciZ0XDd0nnyqOCTUgY7w5oILdIo5DD6lpWPgDE\ngN3fUV4FI3ouL5YU+wDX/dY+qnpknrGAVe/XtZ9bgcbnp6fh3y3/U4Fqfwn1\n43XAJgQnnKB08PyiNByYNpPa3S3O4jYTrv7qY0fF+NqcMmvDnjxAk6WuDj/7\nUEMWooDD5AUJ5azdKx2HdYmtep2qxUqo//RFHQL+55vwq/Yzs4CAdyDwf3Lg\nus6aaT3/WaVL2xr/VROgqMB02WTRExXyFCI/2Z6NVQCKngfDshgsVYyX/CBj\nioJCZ/KdNbrJjAk2Mkszf3L/ml0oExGL4o1G6NvC5ibCwE1eGbGXD0QTCL9Q\nxWxH/hf60vHMmoHYnGlNR7eSbmOWbxphNaRos3Y9LLq8vR+M4vBQ2LWG/3MG\nWqzt\r\n=CThy\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCRTrUr5GgaZXSPxL5PVbLcFvDJnV7hU1FcRnHmkgXcxAIhALJmmphoRzhudSjoX/VE/DgODoNqBZ1dWwThEHJAwBoY"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_9.12.1-without-cli_1584013797505_0.07611728062632284"},"_hasShrinkwrap":false},"10.0.0-without-cli":{"name":"restful-react","version":"10.0.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"ffd09d37ac167dacc86954b1a7b7a04fae22cec6","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@10.0.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-IZx73LEQbBvmAUXOo7Pi5id7/4gJlZKrUt/h6d2y5bV9bg1AgNLeGQvIRwWzXfj5hRcJMcCIH2rWMDJXu4XZZQ==","shasum":"94f9968da69f764803c04b7ad77a2f12c4ecd7ad","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-10.0.0-without-cli.tgz","fileCount":47,"unpackedSize":489082,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJedyiMCRA9TVsSAnZWagAAktAP/25SavxT5UEure1sk35V\nEGUb3lomVefughOwSxqU3SQa0v/cJri8BBTUUsctKPM21ADDRf8ii8DFVeyP\n6qq+J2DsXtjAvCmAdfSyS+X3/y/Qxbc9dXTJe0MqOFWpHXBRnZV+EVYFycik\ni0/XurJ6i1X3/VYbDg7FkW+LIhf6BqTD+4AXRM4RjMMoI5s01+okigsE3P/g\npHTAzSwAtgj3ZNUDoVJQvFmz+R+xLbylHl06K3COdJTG7x0IgyzmIH57a7+0\nSu0pP1Cap7d+qegb2LZAOlNmMo5TY3G4SfTRua+K0NvLKqDf3TwGFr0EnqUM\nrUno2mv36hg7N9OhdR9eKwVzClG8dbcOX5Rw+9+oDRdnbdGxXhzqlZgNXBzb\nXw8RWrOnfveR8KwebZX64LTP1RP31ZHpTz6FA9mkwXYjconzs4YYdifniO9T\nQ73EeHTlWp/MDHifPuHhcakx8dab01/FOwBhZfLBDm9pLy8E8Z1TRnV+/WR+\nlBekPkmAMoPoqkKMYSKrQmBQU/LInM7aNZbIVo4z+5HiikGjo1YP8GB7y5jw\n5Bfbx28QR40ThK3kb44Vamis6UMcJ30wgv76CVe28+IrW0sPnTKTPB7QSEiN\neTU2VETkQqa6MzdGUkD619bQtHGt75bYFQxvbFigYZxgaZAlA8B+d3EDUrnW\nCvpd\r\n=4iDV\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIAoD6NXFUJdGnxfwEZFOJi1rtAh9bmjJj9b1cLtqH4YnAiEA54yNV6AKrXNpGn1Oj1DNv+DutUerSvq3qPAuoHzuAuw="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_10.0.0-without-cli_1584867467776_0.936258456655088"},"_hasShrinkwrap":false},"10.0.0":{"name":"restful-react","version":"10.0.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"ffd09d37ac167dacc86954b1a7b7a04fae22cec6","_id":"restful-react@10.0.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-PDJ4/IUrwwP05HAmY5HED0w21gN4jcCFY+RSSa+J3/FvoO7R70REG5Dv8Lgjej7tUiqHHgjK6aDmZJMsyDZw3w==","shasum":"2a82edf82687da4034ced02115d00a832c150c10","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-10.0.0.tgz","fileCount":57,"unpackedSize":540022,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJedyiXCRA9TVsSAnZWagAAm+QP/3p5bhmYbmY/YkIu5/1S\nGtzf9teP+ScFV5qeVaBEqQLhHJpkxrhPqwaAxBtKA5+HwwMA4d8XImtlHdnO\n5u0eV6r6UtTy+ETouZ5oVVdz7NUubcj0NVGAj9B6Z7lRt/fXWYxnuWeUDFi1\nxD2QUrdMRXmexiYpXujDOjLIAasi41REUfD2+ySchadtxnrjhrWkPUxXGU99\nXVlc+I4vk2aLZWKs1z/JR5vOuq/ScxspRAcjVoLn+73Zk2SwpMFyD9lx0kmz\nDsKH2nzfiSN3M/GJrN/FUDnxQXANn4+mFR8HrPGv/WmwXTanrhGufOe5uMiO\nAQ8zWS7ruZVKU13bU+exHzDpGMncFfOEQfPjjQKXKXKR1b8FlKbI/WLQ1iaL\nLSzaZpvD62VjhiR3bv7szv0rqlFVxqx190wJRi/lFeYTVTPdUbWL6fZ7lfjs\nVDLSdnHBhMsgvJPGhpT1oWMPf/USRgIn/+CxblnwKlzNjSFHzq/ChHNDHszp\nEoVXaX5pSbd6+tNIxj8t38XBEyL/Q+EWbaPnrRJqh93Z8rBi69P1s5m/SS4y\n0C/daENR0ecY9GKejs1AKnPnw9/mLQwAqmV+1IjrrlbfSoZ/9FLZnx6laVkZ\nLpSNtKSdkAqLm7l9npqUQ7VCn2u7PWi29ziMM4s5g/xTuiurGd27iEdbLpjP\nQQVG\r\n=ygO2\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIG32DYAJ2viG/7jqMFds0U7kOBuL/wnmam4pNc4OceB4AiAfF6ul+jg41isUNu3onrHMxQ5GghN/fbSO8UY3kJ64zA=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_10.0.0_1584867479439_0.3974724111581682"},"_hasShrinkwrap":false},"10.0.1-without-cli":{"name":"restful-react","version":"10.0.1-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"b30a2628fcc63614be800010237fefdb37cad88b","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@10.0.1-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-pu68zhdXEzCYxMGj1rzpxdvXHCrITHEktSYd8cPDeiUqrui/ecCU70Jt/VuBh//8STxESUronuU02Ey7mvuAow==","shasum":"4e5cd07918799a641c1e08700ab885b94a368366","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-10.0.1-without-cli.tgz","fileCount":47,"unpackedSize":489082,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeePWWCRA9TVsSAnZWagAAGtcP/2rp9fmYiCPFEPdgxGiD\njBPxUThPqYPW6JBXSX8FAKeJ4s1uwUx/yzW7Nyrw1qzTvI50D5dRdBlb/5pH\nMo8n/oywy+t7DmXbnshqprfMLU/Fmo5co9EnuyYolg7y1MvfPEnwT9/j6muf\nMWSWwos5l7wryspLj9x/7pDqPaZzd9G3MtX6eEg0DDzrzGZfneAoVaQqNMiy\n2VQPKz4T3nVajyaRIEe1l50mSIV56BBV1gxMG4kt6MbHZ/8mUoqbbWATZ6GI\nr9Oai/WiVslZEKqvmGj+lYOJ8to/EMWRHSPs5SZyfYIniS329UE8PNYJ3dj/\nqGTuDIj5/FWz6Pl2AsQT38lk69v8kLPtGlRF5yFZJNqPeLsW6qL1eMvRplfc\nTncW64eOgzvC46Fl7iBKZIEOO5T6v1w7TXHzB6ILgHGR/EvjFw0ICJRO4Pfb\n8s8NENetmptVdrdSO2QJj/5XnXt+u+4vGtuBLuxjRGlLZPMlTmhSiPvqMyQU\nbzmLU2suOA+6aIxWZT7VKufK0J1ojPDXOreycSWRz0Bffx6e4S0HgN0f087D\ng0xsnXQf+Z90XSeoAlXOT/ecJumRoyqEoYsEpguEpi/oQB/L1TYqHWAR9viG\nKL6Y/ghByjEqPK307Rp90A0IY3jLuc60tEDsw8v6oULpGBBCivjiYCYuHJGQ\nXhxZ\r\n=+dij\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDzcAHLADnTIuV0k66yqShoiUBfbA/b7+yTTsNZIap9+QIgZYbDWvOvN51e5XIbm69GBz49C6vS8N6FESQNIi7tEd4="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_10.0.1-without-cli_1584985494234_0.6948522882141837"},"_hasShrinkwrap":false},"10.0.1":{"name":"restful-react","version":"10.0.1","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"b30a2628fcc63614be800010237fefdb37cad88b","_id":"restful-react@10.0.1","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-9EM1deMNXlOD4Dvz2a+EZBJj6Al/VckOUa90oRJNQykwb5dAZGNxnSKEU2r4k2Bg7O5HA2NbJoZKvD5hVnN5Xw==","shasum":"28d16be97625edaac213daf65bc5e09fc163bdc0","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-10.0.1.tgz","fileCount":57,"unpackedSize":540028,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeePWnCRA9TVsSAnZWagAABtIQAJWa0ru9MryA+WjMiDMv\n6EKq8ERDa42P9l/DcOduXN+eLMMCWjzD54w6oYYLYIxOleQU49KzBRGi9enL\nL0eShxufyFGB2Kmw31APVK+K1L+77dzTCmukFNvtORnMeFtdOUPto3Vgc0+b\neTaBJMNim82D6wCyHibFEg9XIIRFO8/BQi/NDDpKFq7O+nxaZyshZCQWlSE/\n3BpaYhIvQv3gFCFizi/aHLGYgd5GunGWv6XrwiK4pIwtYN76Wig1lL0icm8J\n0CFvYZM609aA9Ff97f6x/TmKM06nbuVjCfNcCTOH04o7K3qtEffxXoRGgIxh\nov00o8ssjtPrIL9Ea2vTS9RIBKM0W3BqM6ydf+SYcjihvid9/ZYj6d/VnR8h\nFixF0U58Fy/kPVoOv+OPO6M+iJQD8K1SYxtEJnwGkJ02QbP+ZZotVU7V9UNc\nJFFOfsuf0qtj40TN8IItLApmMNNLT553a45XLktlZxNOel6KRutXuvYRhaV3\nIxiIMuQexM9CeWzjEb0INfNS/DtY6OdHsa5p9kvSifpO4a4gAxRKItcpcmml\nOFsZV3w7EY4+OtYyqg9JtpTfglxV0sSXlTDakhcSoNlybo6yOX0thIKl2ECb\nQAfyD22mm4NPq6gP9GVbvi9ht4fGbk/AWmlMQf9gQlqXbQpAtor6CluNwvrH\nEb5A\r\n=Z5Sr\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCzs3Jty8WrlDnZWmK8tQyGi4ClU4l/OSTnNbjIZbzDUQIhAMKFcuB4A67pNP08cJSG7iuCFtDG0OxVYG+hKHlzMI7j"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_10.0.1_1584985510633_0.7591752142554555"},"_hasShrinkwrap":false},"11.0.0-without-cli":{"name":"restful-react","version":"11.0.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"6ccf65186ebd63df93c3a62a3a325e0c3dc187e6","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@11.0.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-Uq8IQeISGjFNvYwFiZNRYgPmXdFPuPIA2/bfZXjgzJesKMYHukzzGeFrstfq3fRw7lH7IxCILzMixNExX2b3KQ==","shasum":"85f92f1297ee59f793e01445b17e85934a7959cd","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-11.0.0-without-cli.tgz","fileCount":47,"unpackedSize":491402,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeff4wCRA9TVsSAnZWagAA8jkP/iikjm9IevT4sRFju2J8\nkKpiZL5vZVucf7Gs137v44RpGV9X+6LM6FjhptuN5gfCqIBd4LclkyOb2lLq\noAkZAPAj5aUdEZqtNwo352MxjiEN0c8vJ1n3onIC0aLbtrrx8IsvHfQ6dpxr\nSxO8kHrmAHxAF7ISNHX/7CLXYTn+sYccsb5QtindTMfMvdT/jtVGwyErEeiI\noZ/xw2iNXX564ckRY/QnYDwXxAApWI0H4WZau+XY9mq6xVnNtiZ1Nn7Xlwm+\nJMY1bfqdaUhMVt4Xisv3NqqR2Zyegd+IV/8gQrT4FSSBvL1mbqPepVSGatwx\nGHWw2umu0zTFc81l2s8DKuaGirtHyynkJigONbCpG2mVzLuWbC/wpJesFOBM\nrUwqdEeXJKpV23fPbiNoFpFfdGR2x/WgekVCUn8+urGsUFrS/IW53i1929IL\nFiQM3agDX5mcjpbfKQa8hidtltHyL++J2ZJqnifrKMJel17oRJx87ayEyL7X\nFx3DsgZSD1kvBg1jGQtvFJ5fvS/TbVqiKB4MENB2zTWw8DKjk17WidHU99oX\nbctc9E+y+/MsA/GXtCmwEZKh1MROZ17CBB+r9GPCGMvfRSdp7wHJ4qvrbihh\nWlKWEfmu5HYA1cmYRaheXeruw4ZVdDO1ow/P0y663lYiWv9n1j/cgahYbma1\nJ9kO\r\n=agJ/\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIAMDiUL/a3QhiXm/R77Gvj+SkRBNJRG1wI+RWXAUarqkAiBnTp8aGNEUHSRHmbFLAZQO8eFVldGVXlf4kB5PgBT/8w=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_11.0.0-without-cli_1585315376171_0.47736321984604646"},"_hasShrinkwrap":false},"11.0.0":{"name":"restful-react","version":"11.0.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"6ccf65186ebd63df93c3a62a3a325e0c3dc187e6","_id":"restful-react@11.0.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-Xk3cNZEof5nQrmObY2y6IpJPfIiyR2F3tSsRyf6D7UtIFRIAXUzhosZSg+pj8i4o9lbC4CBLeuC7SiwIYjcSrg==","shasum":"fe6f50414b954cb4ae5cda77c2040bbf5ab4c4af","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-11.0.0.tgz","fileCount":57,"unpackedSize":542348,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeff5BCRA9TVsSAnZWagAAT+sQAI2iB+1BTsqIrjTn2KWg\nnFVNROJQZGtdN7rqG9FZt0hc+Be5IGKISu3RkWP8OvlCWmQBX1T1YrpexB4o\nhpLsYz//tuBwVIJSyBAXDT+7700v0/CBAmVNo+4zcbxeS917NY0R5RYV0cM3\nsBOjJPcR26BuaFjdyuRmOAIl1D7rw95ItKqj9LXunSPBRAjdsCL7gYn7MMdV\nobcBOpTYP2WD4NiyEUuZmtyJVY+uANrC/URa9i4vUDalUKpVVyy8xfL1Hdcp\nqVx1g5kWcyCEkvqXfblsH5fThh2GDTIPtjYv5GdIzbUcMPlkMKGZQRxGASIR\ny8pUxlPqRt7VH/FE7FaMM43gnAm+yivT/wh7rBcPLiQV8x79pZOosLVimMtY\ntRpEX9b7V5USzqBGvU4mztwEpRwTsA8F/qLl/EadxJNccrAIYLr9/yUFY6QV\nAY0GioRltVdHlbvBiAf7tWE02vatMv8obrlDlb2Hy3SfaCB8zE0RH6AwjKhn\nWkm2dcq/XPIlI7Yk/WylxOA0oNvxlV+soEZfuloLXz2MlfMPCKu7pBelco/+\njPWF/FfkDsmQ/POQr5kCDpJX8a9CM3ni9g0cRgUmtRT8MhIyaGLBIZC3E9fS\nFSX06NShVrupIhBj7Cwm4p65qmZPjhV89RnmgZyRHsBjZkhBo1bLUkkOUg5G\noNjl\r\n=WMlr\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIBtgAPeGHYB6oYzZVGeP5W6r4uoHXQ3brCA5s3ikZwudAiEAsvi+uRohKJA07jydrR/hdpzZUdF1pT98GKCVSBwVJq4="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_11.0.0_1585315392677_0.6076197955071534"},"_hasShrinkwrap":false},"11.1.0":{"name":"restful-react","version":"11.1.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"2628bae152967283dc2df5f4cc4bd29381cbb919","_id":"restful-react@11.1.0","_nodeVersion":"12.16.2","_npmVersion":"6.14.4","dist":{"integrity":"sha512-didUbkx3s33Pm/eUMkuXreOPBakjOQ2Q6DyQoYfhVre1ehPUm66oG5iufeC/mjoCCOpjk4BIdxwjc04N1nlWkg==","shasum":"a602fe90c7b2af3566f4b13be37d49c554c1a662","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-11.1.0.tgz","fileCount":57,"unpackedSize":549720,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJekwrKCRA9TVsSAnZWagAAFssP/jbp5RENfRIseHK8IByn\nTeiG25CPvS7NAfzyuiZ/R/1w/kUQNfaGBvO1+imbGkSQRJDlCkI0DskLqI4I\nABL7Qv/krHgp5yLyxi5kKvWLnUFubTc/mUORWXs2n6ZAsFLol00u7lc/TMCQ\npADTQh8Ixt6pgh8510srPKUnJikSwPV3LtS2vVEvlwVlhkCWvPZZ2bLW+iGL\nSEJe2kUUBMS3Hxqnp7M7KU2ZctWr6aWkPbZwVH5pKOV7jzbkpzrK2fIyngY7\nF8vzOKnkEppqWLFs+4Fypw/7N9CECATV6Pxiw1IHgZT1szrkl0lI3plRYbyn\nKnawMk2IEVqKGaBwGsagVMCkpzBb8P4+NTJujTSrlBQfM7uQIwMMzB8sr4Jd\nCKxeqZsWeAjB9HoVSZEHMc5xysjvFxsIAN2286s77L6py56+vsfnDfmW211/\nLvUF4SKbCSMVWExwZNUcTYOxYPhHKnl9iumkQin9DsEmv6ifSnaCh2p2oqfR\nRO6fTw2p+7Xbc7z5wuAQxFGAewtrZfb6iIDqpQrBk5DAkhwRIudRH2uF8lSb\nmPtbaGvnVwKU04uvonNdFjFJceP8fEBQK8NdFyhUGMugi/hBLThP0mqWo4wO\n7WOTkn6gRxL5n7YSuA/qYs5CZU306YSQ2B5hMGePvrNY0EyzsCNwOtxQtYOe\niybB\r\n=m+Qw\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIBbqRj6qhd9Vqb9ivD5FbOSQxpvNmGiD5kLZVBPRp+OyAiEA8sXzVWlc6aQPKeJiD5M9AdOcJZIWhvamyLoae9L+3tk="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_11.1.0_1586694857829_0.20618997697920194"},"_hasShrinkwrap":false},"11.1.0-without-cli":{"name":"restful-react","version":"11.1.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"2628bae152967283dc2df5f4cc4bd29381cbb919","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@11.1.0-without-cli","_nodeVersion":"12.16.2","_npmVersion":"6.14.4","dist":{"integrity":"sha512-vv8Ec4d9X+i4fy0nVLg2orwOm8MVDce/C0SXl8ORkqK02JkBXqcJbMQmUgesfcqrOr8txc3jrBwzl9ShDFL1nA==","shasum":"c7a77ebcade5ba253b3517ba1aae13bc7b1ebe63","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-11.1.0-without-cli.tgz","fileCount":47,"unpackedSize":498774,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJekwrzCRA9TVsSAnZWagAAuCsP/RrUAVkfLzjOQsWo9ZH2\nrTH0K5WEIFfCGuLgEGnGrDTYp1shNw4HYZpoAyEOO1nk/EUWy+ohWeH9FnEQ\nx/tNL8mXbLHy44QXbudXe8pTNhbeZkjXyz0IL8ebrtzviqmO4cCNl6plhiNm\nSKxWzf6XonGIU7t58ewR9r86cyXRWisp2AEgSxq56adqJ73VU+r16WWC+XXc\nY/CGmQpuK2bwRdNAP273Rku0OckwincFU9jumK+tRtT4Q7cAYDqpu2Epuil/\njuhlnhaPgshs81G+RvfPavR4NXWNpX+v/hl00a+86geuYUBnwpWgvjfeYKIa\neaTtVik3A8elFuvZ3qihTymbsJi+cNuf1EbXJtTXQyhfZaW1c/xa4Vshcwhc\n55CCDXruhxTjGeX5lpl13i4neBFPyJHiek1ksmbvznXM7IKqQsEkKEiy2L0y\nWZvBdbFYCLSqUrkRjH0HqLsm2ADHIDjsWuAtBkIxiRbAvezJsxad6I9VPFmM\n1TDJup1G/0AYbvlHm5fQ0iE+ci83EYBuneQJE/dlh9aBcIu2EOe9OID6pT2X\nkkLVbtGhp/oTeqszRpTBQldJGtjXMGg7BlooeXYzF5/mc+OrNUb69obCl8a9\n1QcEs9ukFiYVzncN97onbJ0//RnV4vtEs2aPjnHyD05fyYi0vF6mDyFDDE3g\n+9KT\r\n=e8IV\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIDeHL/soI5KHb3RHn0flLqGk4pSjYtucYhOi8vQTJXNrAiBA/mQ5FMQ5pZ9XEWUaKryWwAfBFa0RKR6GoLlz9LSPbg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_11.1.0-without-cli_1586694898791_0.9671907007376577"},"_hasShrinkwrap":false},"11.2.0":{"name":"restful-react","version":"11.2.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"1e4508409ca77011d39dd6cde8be393d084f0fb7","_id":"restful-react@11.2.0","_nodeVersion":"12.16.2","_npmVersion":"6.14.4","dist":{"integrity":"sha512-x0upWdT5v5EwKRj9nMsfnsqioKVk41drG9CdHPjstqq3bxeGWHZwtIyFikwenuMGck1o8KK9kI77n8Cjcmor+A==","shasum":"fe365b85a6048bf2f3bcaf490455a5f32c5d3e45","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-11.2.0.tgz","fileCount":57,"unpackedSize":554782,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJekxBdCRA9TVsSAnZWagAAJC8P/iGJ9X1D0zNdr23ONosD\n14zIbTNX53/AsVA3T9rQjuI4rYfwAuP0UzYfb8tCPq8XLHcB6ly/svdANBBi\nYmruCCVJeywcKi+7fHQJdKtb71nB+Oi6QaCuz87GZKrgNsxziOi3feKTKAjZ\nS01sD2giYOp8yJ0QM2GcPT4CNdwDzDIRLZ01UgUroWN3G5ip+XZewqgPwqBC\nygfQMi6PVp4Wmr688D+4Cx5/y39QxSBglrhUGWkUeWMo8kl8NsJqn0RZEvQ8\nEYNXRPmu270Zdd1zZsYS8nOqp9n5/spUS/hzIlxbnsartjB5+EqnZhw33OZ/\nq3lYBidTHqKHdoXxA02Gp9TEHc1DjERr0fcValCG33kVlrDsdae8NStUNjez\nWqxBdJhUEm9br4BbemRzXWTEHEl6JArkqkfkhUktq8Trkav8d7FQPmOI2X2J\ns656ze6ij8/qod4F1U34yjXEsmk3DHOpnhM371CefXngHXNK9rOaxWMDmbaO\n3SLK7TO96rSlxz/Gk4rUwVUMCHCPaVUN1znAo0U52YoGzu87Pmbh8BdJ93gc\nvZV99sKaMrAjHbNC4Pf7t7pFtJymQ/+wGWU57jzFyExQ5G97GTF0RGmHa0pI\nfa6oOZfHs69dzvLjRNLTRgG26PLEGOyGfq/+wtw6qiZCZCyMctOIDJWwd9VM\np5Jx\r\n=U3OF\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQC5+FMXViBltc8zJ+k4WzH9v8HeYkBEzp48F4JoPGpcIwIgTHYtWsu8IJBgjnOBCrR9i3YMRHRjfYOSvlNVOzinHIA="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_11.2.0_1586696285309_0.20233991990735212"},"_hasShrinkwrap":false},"11.2.0-without-cli":{"name":"restful-react","version":"11.2.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"1e4508409ca77011d39dd6cde8be393d084f0fb7","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@11.2.0-without-cli","_nodeVersion":"12.16.2","_npmVersion":"6.14.4","dist":{"integrity":"sha512-nE5p00h0VJHnlWkE0HggHy9n2SJc8pgt8GHSYbk3NUgaBz4nsAO/vQXxxiPvZYii8vl+v4qhaESQkkhnMwrryg==","shasum":"ea33edbb098cef2b4216f08b422942f3df475ce4","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-11.2.0-without-cli.tgz","fileCount":47,"unpackedSize":503836,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJekxBoCRA9TVsSAnZWagAAbfEP/3cSNK0OJjD40yaN9iF0\nCwn+DUSZRBcIvIncX23w7ihfzbZnEdn0Mn0oUbD+KIwwUdEqIXYmJ/njyhqu\n5uHTFv0XAhBOEH/10TVndMVtnbA/5mwPHrlalzh9XtXlXU94hQVYUMqXSLrM\nwgsfbkxFAI37u69qphzWJBZGrVAh0xedNu9D+N9hcZfviYOtRGt8ZaCQkT8Q\nTxpsfoMM94AA++4kn/QtC8VH9dBie9bh2DrqOXXF5x80LawU4Knst6eVaK96\nPcge0Mh4kDEaerflhQjUkIbtly6vsopJ+yzZidkxCWO9rnqipm3jYNjrP8EG\n4Z6axSf6cdsnUS97nENHjpgQPdfnsKQA+xN8ck+t+5o+aL6yPL0fqwvTHpm4\n07N1CpLbtsb126bX4HIX/Wzyux5+heHIE3eL0Df1q3MGuCMdnWVfS9LMlmql\nrYRDrzPL8A5OWwSbZi36KmkxLmJ3/fl/bxz3XvVXmQdnnc/dTYLIoRS6mPLy\n4t1NtjE8KDM6qBxI9YipPb/PTWIaZxcA+HUmgM/qI0m11CbX89V1OkHrGWDU\nZcuuDRExjGikxRrV2RxWzP1pjjl31Qzt7Y8cAbNvOedxB9WPshzgOn4my8R+\n3qO6TXK19Ji1taMQVJ9xsGKkRW/US3SYuAMIuPaZXb/izX+8czT7LP4JqkQn\nPgoF\r\n=/Nr6\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIBbE8sCsQ83lp4dwJREqmKqbW6a2n5n+tLAlVgkK76hfAiEA616xFSdGvtJIJgJOn3bTTe05HD1+pfz5Avhcun6QeCE="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_11.2.0-without-cli_1586696295953_0.6931363997616429"},"_hasShrinkwrap":false},"12.0.0":{"name":"restful-react","version":"12.0.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"12d905cf848bdcee6362b6aaaf496dd3d1f90d63","_id":"restful-react@12.0.0","_nodeVersion":"12.16.3","_npmVersion":"6.14.4","dist":{"integrity":"sha512-GxjxfMTfhy9sxntK8eTQJOUdOHSWCYslg0R590VObh5WEo7k4xtflrIytcvWnKwhblcFo6G+UmspYA4AddlJeg==","shasum":"a06757b62b8990014575b0c398d53e9a350a5289","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-12.0.0.tgz","fileCount":57,"unpackedSize":558417,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJer/t4CRA9TVsSAnZWagAAT4QP/0vULTqqFJCj7jeqUzhj\nxAx/ZS8cTopKy6CS74PVFKMEeHpcEQ4CmK3Wlx9/LffkbutaYEbDGFifCTwq\n/K183izg8LA0Go+IuLAAjHk/6coX+WQ2P0p7EbLL5OJp0CuJGiB5cEhtivPa\n+1rHRRHfa0XuJYfpQ0ZNmC1LNLTo6D0hI+1TYYuF0x6OyREl2aOwJI+7MdkE\n1l3z1fQPuEOOpzBf3IqhWY5glv4ndphDwRI0tSu4+pnt5q4ydPEY8JjqNvJg\nwSblt1xqrZ2D9aBNi5JNdGA/JKbyBMVWXDQ7FbfUGgcYPDmA77Z+TUt/Qi/2\ngHfWPySQhHIxrs1eWOLTEjdwoyMx4J35CpJnCyQDbPdi7zcVnEfbOoORuqGy\n4k+QsCcRhi86oxTYkUEKbQnbLcXe52Tgrnk58dCkr//x3ucewuaLBX4keXm5\nt3ixFDCAtQXRbxt9VB33LMCM0/xdcVI2tMIIizoQ6e5FdchSTrCONDRNgrvC\nFkor/6ybX2Yx8CI9wbePy+PBNnAecIef0HJarSotGHKr3XBZdRmFhz5SUZ9T\n6/7Ca1aRSl96DUflpo/fZzZU9wpUMvRh8N7V439oKCLCHMw2Y80cVc08KeOD\nCGYL1aGdSBSWuI47GewoOfHQLdT5k3SRccaLV6RKIb141bsAGGIeC44uLGHG\njbAt\r\n=CKVK\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIHlO+ot/KFRBPntLzUbIBHUFOeyHtIbBuw5OR1I0isn7AiB/mFmmq0fYzuHbD6s6MDXVmpq2XpAwl/OLpYEBJaD9QA=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_12.0.0_1588591479998_0.5528479565605005"},"_hasShrinkwrap":false},"12.0.0-without-cli":{"name":"restful-react","version":"12.0.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"12d905cf848bdcee6362b6aaaf496dd3d1f90d63","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@12.0.0-without-cli","_nodeVersion":"12.16.3","_npmVersion":"6.14.4","dist":{"integrity":"sha512-wHTtdPf9gpVz4v/KVf9EeXxcmBLje1tmN4iC8PLgouUD0Kwg4+v69VpszV7MCnwmDTkvnBtvyKlgIpREqMhHug==","shasum":"cd7db0018e58738afdca4cd564437fbaf64989d9","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-12.0.0-without-cli.tgz","fileCount":47,"unpackedSize":507471,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJer/uHCRA9TVsSAnZWagAAERUP/R8l5VnGpTFv2eHgphcH\nsWarZbadktNwnbjS2Mez4e+fZ0g4MK6rRAssxQFXEJWZ0sAUjMnWOhz5FpIT\npFw74JXIJw3SSp/duesL3AbVoqKx7ff0OFCPIvB2Ntfoo0X9F7A5Io59j/6f\nxce0xpStav9b5luGVIjepDAX4pYxlTtXIpJLhKqPHVY6cL+NcWGk9LcB9DSZ\nx5ZdQMdwSnYgq4M1UWMxVr+QTrgL2j6Hi5G4myW+/dYa1xGRmQClhrHm3cep\n9RLnXSjaKe0rRvXzmuSLXV/0SdOwImKZUSxbPfelrJxQHdGHIISnJd2+zuia\naaQ5nVSzNucc03UzJK9EIrXvVnXK4qTuWSWPDSRFDUquhfjd4n/GPm28LB62\nOJAW1egsduQE96Eyxv6fCpV82VoPjShb/u/Qog7jiH/5ideZhvaFyry3N9Pt\nF3n3duOYhTlUPOBc6WRqIhnfUmKL+wiI0hSnIe4vdUFCYuNQ2krx1xim4S2a\nk0vylToxNU9n2SKFqqbBUioowLqSQF+5rTKrw117OoZgsnxgvkQ0EXnQW91v\nyo3Km6pMiu9LMyG3mtQtl9g6c2iV6DVrA6Fqgosarx5L3shrXXTzM2609WED\nyloPIRcm4A5OERJ+BVZiazJIiO0vVhxbBt3DET96IQbaf5tGkcMdsaWPxFhO\n7g6b\r\n=wEAE\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCSmg8qY43kQrYKyAzqsHYBI+ZKLYQAclVNizMTyBuXNAIhAOiAAN4OkAKR90JMD+adZW2bZt5JfpME+5rwThENJok1"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_12.0.0-without-cli_1588591495534_0.15022927777103745"},"_hasShrinkwrap":false},"13.0.0":{"name":"restful-react","version":"13.0.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"5320dea4c4968790b52b598ac0118c51edfe8f56","_id":"restful-react@13.0.0","_nodeVersion":"12.16.3","_npmVersion":"6.14.4","dist":{"integrity":"sha512-9WbFCD1Mn9yklLLe8+FcX99xYGkMZclxkuj/dndxfMag07VIL+fV2h1CfFw6Yj2am/1vALap6i69N6PxzMKaUw==","shasum":"0f7fd2c98b852c89bc3712493243383eb1bfaf0e","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-13.0.0.tgz","fileCount":57,"unpackedSize":569962,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJe2kTYCRA9TVsSAnZWagAA3lAP/2G9dfVTsOrg1EnVOiqN\nzpz/DVq5ZCC7v+djpv5yH+whfAywsI3MwQa0/hLbT5FcgDcfUvcAKiGeOotj\nvyzsEOq+ckcClfjMaW34/fUMWZwvaEsEbf1r5ie5+rxCJWq1fK30cnDBHyRN\nGko93wJyH81FFry9UeRDvBexbZSJsmfpJwtdwi7eabzj3ljOEn/qG/hBiDZn\n/HRF2Ub9drDPJu05lkTNjP/l7EjRYsij72NXgoMthwwPo3xSQuW43kEiLDGm\n1cFJ/3T4DVsXsXdmk18W4kgSPnayD0cwaJXxTCWPbc1Too/Ni09caoyBwV6u\nYT7UYbm6wcNStzeh4LYDp0nwxSQf+OKvDDavs1khI4YDcWuWmzORIJYgIy7O\n7p2CH4wUfFwy52OekeY7kUGwn32kc8VhhhyeO1Za3mZ8WusrUKmqM+eHsQ2z\nGIFzmRxmnHrVrONz3P/tkUnWA+v0/184jJRFY7DbPZrzCsYRdgVTGqjihqHa\nlk91dmDngKr2ThEggcS7Wue7ysk7g9wLZuDGs8uZ1UOsKn0DaR/z5f371whz\nkq8Mk5uNRif55Cag0sG0ePUJ7T8Jkbvwt5LotbBhx7D9tLhpGRUaw3baQe2o\n4CZ61LOXIqBJBBaeexWQ2sz7h7XOfDxTtJvRVIslXMde+Xnxkqd9IU8XZQxl\nb/Us\r\n=8zpo\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIHc90eOGHkcb085jYrS1i9c/REN38l0Nq8IEi+rwhui9AiEAsBpFV/BmYFvAdLHqKO1ZKzjt+61g6fIaajeyDewPDqg="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_13.0.0_1591362775615_0.6447598956142937"},"_hasShrinkwrap":false},"13.0.0-without-cli":{"name":"restful-react","version":"13.0.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"5320dea4c4968790b52b598ac0118c51edfe8f56","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@13.0.0-without-cli","_nodeVersion":"12.16.3","_npmVersion":"6.14.4","dist":{"integrity":"sha512-potYnwdVl5FkxDBd67eKPFNx8lmmOw1WDKoDLm6hpOjVPfoRMAIKb4Il4PaJgDXdTk/VIiL+P35deCg82k9o5g==","shasum":"8a6d58c3444e0cecbd43108d83362e78779921ac","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-13.0.0-without-cli.tgz","fileCount":47,"unpackedSize":518157,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJe2kT4CRA9TVsSAnZWagAAH+4P/Asb7Vp1bmhoiN8a0sgS\n55K/9BcSNoHY+C6730tVI6t5O8Itf8pd/oL0a9wsT0PME1OmGKD9gKb/pxT8\n918GF8Qlkwjky1TM+bgFWMzVBRA94TNKaGb6wbHDuXnwlDWNTnDRoGqb8YoW\nolJq/8L1I7FaaUyYSaOZQO8NdlEeH0up8O8fuV8aAjahfuqeS7CJB7KGimON\nNubDkQOjHky+KJjgJwraXbz5C+IhzmUxjQ50mokS236nhvK1TbpkLVDu6XgJ\nFsk8Kpq7zdktHwa07Q5Pt1AO4yP3OeoxYLC4z5OLmJ9+d2GO9QvtqeTmHq1m\nno5E6sCwlWz15kzdodCOK0v2DjqapepCLieEgt+bTxCVLr/mbEZWIq+xpH3K\nG57uCyIZyeC4hYOX5DQRePDhvjE2xf3WDPErLEy3+Y8sfD2jKHC/frjz5r62\n7X7HtoMJWdQ966086MFX90UXCU2eKAmWI+iUP1YH71XmmNk3sRdnJRNbMY2c\nTt1UiiVkZAIskSlpFHv0NhZe+eqYGHRrrwMITOu1G1QE/gq8vcBjnPHWalz5\n9CCEAtOxejKhdW3K12vszYI1U0z1FbGAjh141aFn4Qv9OYfJLgKSruC26JB7\nvN2CIkqnT4YJrsVS7mh/z6Tanc2/L50nqHwqwPsx3CJO3VoDqhQjEGJjhAtc\nuZt5\r\n=4r9u\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIH+/IF4f+j1e43h3RSTtq6w7y5WoPd7enrdh8LNPHtX5AiBSSuZJ1llZrJgfrJ9sYF7ciI3E9zYNItO++LvfEMTNXg=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_13.0.0-without-cli_1591362807915_0.037112900443364794"},"_hasShrinkwrap":false},"14.0.0":{"name":"restful-react","version":"14.0.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"61604ee50626b3c910224225cf4dd92cf4b260b0","_id":"restful-react@14.0.0","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-+AJ09DnOU2fQPImlxwLJD1yeQik74eNvmsUlnZgYnUQ8xveedtnnc0QxpSxIfNIiFiKrqC3KARltlCYgppue+w==","shasum":"323b3e5dda6ad9c2a895d893e14551afe3b91192","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.0.0.tgz","fileCount":45,"unpackedSize":569683,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJe50bGCRA9TVsSAnZWagAAgNQQAIJL24QbMXkfqI3H5afp\nIgMVD1Hk7eR7oEBWvQW6gOTn20s0zxbbYWbLFNCBtJaN+A46q3W8N9B1kF1a\nPVPvP1tW11Uu3ITUW75uYe8CI1uejr0nHvfFwHKWDA519TtcQv2mS/hfMmoZ\nUM4nu8Ij3lZAp9klc7EQVqBMZxbpifcuKWGzpCm+Pp7T/Qmvh/nqDu0w2vYC\nH1PTqn5LkyyLhcZhsXKQu7JBURa6C8otVVHbia+juV2XxvNmh9qhrKKwvwQ8\nTfs993Ht4e2uANPBKZHXANvrIad22fjf43nf15MfCwarXpqIiwNuZEgmKnFX\nrEIc1Lk/HUA9QWsGuUEwwmmB/bjpr6Bnly+LKSiIQZvmmts+70rduruY0REc\niDkp+Na8SDu3EswMGXsF/akCmVmLHQpUkTMaX9J3xY46rXd9maecznm1h60Z\nDgkOOspH5PPC0Z5IyN7oOXVxJFKlI6QKtTlLEZP2vJEufZ6Ri8BbTjTdQHhk\nxOaTwzeWsPm5C58q6ixlzZ4G5IHs9/ksjMgSnDP/6VC9zsYr6Sth2ilCeldU\ntOS3tgcCF+fVnedTBGrbn+MFIVd+1XU7Pei8LP1ZRZgjEuSlSmHTyN6+/9yZ\nTed2BhyLxtPyV3dTd35dBC0wYbvO38Kir4srUYEPNAoCG2cMuF25Rc1zAIAS\nTAD8\r\n=H5QI\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICVkuoUG3ynpJBvBcagsRY8didEmKj+f7a68pMPPV/y+AiEA+N8yWIVO+GPjzid8PMQ9fbnD9uVS2o2m77A95piIFrw="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.0.0_1592215238442_0.6300104366144512"},"_hasShrinkwrap":false},"14.0.0-without-cli":{"name":"restful-react","version":"14.0.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"61604ee50626b3c910224225cf4dd92cf4b260b0","_id":"restful-react@14.0.0-without-cli","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-Hyb4+92TO21wk6A3tFtnSbu6m2CdADF47rxqIahWGbBjo5R5NGYRLxlvpNWAp6h3gwnpPmTYGPBWAa8GzcVXtw==","shasum":"f1debfa31679e3f99081692a3e3fa77649e60c7a","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.0.0-without-cli.tgz","fileCount":37,"unpackedSize":517202,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJe50blCRA9TVsSAnZWagAAKucP/2WPfpC0mu8cok/KxpI8\nNHc+6bajpJX+tI++4qB+A1ZGf9fwzJ8FyX4Y5l/eTk+AbvxRhZ8k1vvni2Ag\naK5WoTEvFzcuENRf0OrkBsi8fYepW0ZZOhRKiXKUHYDgX62EH9t+I+TB1fQJ\nxUMmUr7aq6WflVSj4hdb+AHpxSIvXvVrZG0qOgdacw8CYFOdsIZl/u/0XlZP\ni73WNCRyG2JtgduJXYzPYlCE0Yo5HfULBZEcgRZWeuIStPSsAMM1eNLsIym6\n4o5mBnNuRrio+caxwHsigz+yUrBMazSaSl6ppH/MFC+d4AzbJsPXyJxqwo7G\nOJ8uMvMwawigLki+dFJwtg9piW4RHaa8H7vqIIwJtfTszbjFcCcyIc9c43Cd\nmimSL3kWIj/56V+Up0MCD+jftx0xgnR73Ng+Eyuv6mtBVmOHC1EoEeHpw4Jb\n+MLSi+zSXBFoOnbRiI59Zucpie7YdsGJsJhF3j19rSPAUdKbEpHr8Ojv99QN\nwJAXmNntUH09nNom539jv3yncow+wy5tIy2F9ZcI/t74MrpP6ntueo3S6Xug\nGhX0g7x4xbMXiwii1g+dqms1OKgdBTVv5Atz8Qs34WNZVmf0nype9NBHDAmr\nuZvcta0kyLOGpDiFn0qYff0ZFdCoC7VAOrDLcP/xzVMyj7zgbIwbAowp8trG\nU7gY\r\n=3bsI\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDeIWGxSHpix6ZM54O8WRBm8KK+qTQaZ/azrNPBl0G0TQIgHmm4q26h06RJFn4TIH2pFqgktea3RnmrEochU7oNbdE="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.0.0-without-cli_1592215269472_0.23206588121999916"},"_hasShrinkwrap":false},"14.0.0-1-gf2ad69e":{"name":"restful-react","version":"14.0.0-1-gf2ad69e","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mocks` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"f2ad69ef48fced3f582ce0c5b259720df5ea5a2a","_id":"restful-react@14.0.0-1-gf2ad69e","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-6W8Ov/AOtPL4XF2jEVwsiem4RvISCxOeDB9t8KStmiV7M5jZyBOg5CoDSZ2IAOzkmpeDZxawCXVJHfnsxGADDA==","shasum":"90f96b4075820800941cdd20bb27fc2b37b35f8c","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.0.0-1-gf2ad69e.tgz","fileCount":45,"unpackedSize":574277,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJe7NyBCRA9TVsSAnZWagAArywP/2jvfHcnfFiRE8xnCQH7\nu6Qmep4hf4ncdnwe7IXsil9NKJL12jvByRQO5VuKVWoYrEXTfNLr/v6FcDoW\nNljfj52QtvkverPpUuID3tdA7mwlSsOOaZ4Mqlz6vo6wolT00GopWcrZKKB+\n3jDSUOcrXfUeZD0DLV7AL47dOfM/EUSp+66FQUXpLWiuSYhykX0VaTr17Xm+\nD1f5YziMUKHohCM9qUubGLma3tZQMyzSfXiVPxGc1+FMD04p0OpOBfvf2WGO\n3y0DtYcmfPTYppAkAJu8h3nGpLLR6x6/AY0LWUvJIULUEkO1EVwf037n3GUN\nuDb/IjTmHyeLVAf4x+8a65DNdf19KYfe0GLjEIkYAL9dUyvxK/C0iD5rVv8E\nl7V9e8ouxk6Hn5ixOS1X25QeWSAsLtaPyZh5KZo/mIwKarg2QrlsHS5vENsm\nUzM2o4PQ6XTCmsHkIeuibkqMEewoCm5Clbyer7uioSCEy6kjbXRtl2eGf4Ml\nj2pDxdL40nlFlrEkWXQid7kfqg95HFxvU0UJTK68E0XrWQ2jJXu+4a7mabZD\nWaRm+bZ/mCHXambIsrCP2ZcNahUcFz7GGbHpWXmOUPngYSQnfvXvcRZws1gS\nWw4MFl5B8d7iSvyIlqMthG52CHeMfUuAiksZsGJFFmGdJRMBcElnoFWTYCHU\ntMMt\r\n=VZvU\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIH91+gaPv9RyUNnOGJV44R9lDPyznPEVBTERdRVUm7H5AiEAyzA8Szm8gR8WfIJY/QjHRv+HUcwWu/PUPwE+pAS2KB8="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.0.0-1-gf2ad69e_1592581248920_0.7486368799828693"},"_hasShrinkwrap":false},"14.0.0-3-g82370ec":{"name":"restful-react","version":"14.0.0-3-g82370ec","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mocks` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"82370ecde88d2b6988c49afc9fb73e3f774720f8","_id":"restful-react@14.0.0-3-g82370ec","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-HflbjFs3MuGf+On3JYOd6zUlMt2F/oYbZDwp7Es3jlUBurnDNLpD+nRkXBchS8uh+ooGLmCH+Ra7c0PyBGwdzw==","shasum":"4c28c07a2fbf222bb3da1d2178ce6122ded186a7","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.0.0-3-g82370ec.tgz","fileCount":45,"unpackedSize":574418,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJe7QCuCRA9TVsSAnZWagAAXT4P/0oCx8MMOJnxtyl1rfZB\nBkQtXOrwrZxCH/Di8JR3dcAhkcV0evtcy5K1tyysOmfUjCMuv1lA35jlzyC/\nmvcXlxkwdWExiDvfSiH7rQqKdWxxuXdt6JBhTdc8Qonhe4HpPIOumIOqGCTZ\nDMYJ7PYh28BPlQokBLRFvMgLuj+pFog5/6/NkPGLjqdb97Xi+OPWo7CGcKrE\n33CveLyP3LoZ+MRxerTiGRlaWTA5SjS3iMkCaAC7hw4evgUmihHpj20z0r8z\nPbkoQq9U90CfH4/Nsv4CjeQMprZlsvev60E+BDt/hkGrJ+LUecbUUGEZIjBo\nuDpPp3uJzR9RpadATlTjUuaOimZjnKqCB7e+uUL6rlGEIs91ej3GP/cGQXaU\nqTRF8wiDSpYwQhJAqZ+s+Msli8hzFzB+lMtHBzlUfTmm/+JT7bHh/2OchbxH\n1jDyU8Rq/oAAWDAt9THmuk1VcDHLqmvh/aG4FnccZFQ6TsHh2c3QOev2LbsZ\neWSRO0XRFG2OymM4bhgwp1iz9ibEZ//ZqgN2td8uI+RHClqqp/jsLl4RUyPr\nFCFsbmDxgfEk6eF/nGugu3YTHn+DYat65iVhjH+hzr1rDD5q5O7ZoRrGmFJP\nlST80tUMmELgq0tnmPN/WcYpZcrBscDGYB0NLNyQTmt7aU6Ux3rRxaWfFEDK\n6DS+\r\n=ZUxH\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICbx7PJqFx4mW/ZQvGTueqQffa2BvEA+iQsLsaJbUPN9AiEA6y7kThRVJ10HWJehEcxbyQaPsnoIgg6i2IbHDO1/flw="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.0.0-3-g82370ec_1592590510076_0.2426380689241423"},"_hasShrinkwrap":false},"14.0.1":{"name":"restful-react","version":"14.0.1","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"02112901d5465086daeac13f806043bb58c331b3","_id":"restful-react@14.0.1","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-oahtiD+MB4wj41Uvf5jhTbSdK3OwVJmdKVZHFRKTS4OoYPtQ/N+Qppoe5MDH4SoX7sjTdOCyFCSWjMW8ypDFGw==","shasum":"56a3f9d1f0b626036284c8a91c314d66e53e54bb","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.0.1.tgz","fileCount":45,"unpackedSize":575230,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJe81O7CRA9TVsSAnZWagAAqGcP+gN7d90kEgA+HiiIXOep\nU9KtuNTK2A2kgKTawEG4zOlIjyWfGiUv5ltP5A5SqNgK+hV8+IVPN17o7OT3\n2Z8DBPAQYLNxg6QnJT7KwlEhJ1IHduwjmf+eCPH4gVOkYPBBR25qj+geLN0M\nsLJvB7lEtkoEm0LHPuOXiRaQ9Kvmzx1kDH0s7Qx08IWYSfwZTeX15iD56G3m\nej1R891qJYVvCorudYisMDrB/6h9wzpyP4h7hl7JWKnLE/DodFit196uOLOW\nZAhKTFA0Fu0hOcY3/nkzUjMxil59vp7QAaON2Ey64/cFHaLqP7c5INrAQl8c\nBuVURXgon3SRQ/L+28uaYZoYuXUHKVpVS7BZL7queq48OgbY+Bum4NStx45V\nTIJbYzOjNA5S6z+30StdP9f/enp/1fvLf6JQOJ0eNmH3kvvabL6UgtjtSc14\nZTWOAx8qQZPPtZgr8kaFK+Wj0HIboy1WWdXofcXuiy8S/nHXzqTc7f9ycNAI\n43UPSj5Fwa6qone49vZfKcltBw23/miKqNSp8gyK/msfX6XwShKNsTNTmhTk\nMXSrWbXEzCCQ+omkknz6mADZDouHSrTY4CT5CD5n+p2Om4Kfq1W4nAEQv6Wj\nafcOQUQDasWWn7r9dnSGAr1Fk8eC2OQLNTctzcheRTyjSgE2vlFKGCVJh0B7\nAJcx\r\n=czsX\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIAlcB+gA7V00CCt6jCI6fP+12TxKSo7c9PZuFqWKvMaTAiAnqqdqg8C8ro0gF90z6S5QzcAyoqOKTsRtiyuTMErLdw=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.0.1_1593004987238_0.2200835373680976"},"_hasShrinkwrap":false},"14.0.1-without-cli":{"name":"restful-react","version":"14.0.1-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mocks` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"02112901d5465086daeac13f806043bb58c331b3","_id":"restful-react@14.0.1-without-cli","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-lyGwsk0QsqMUUtZ3bLxv13HW1rvjQRZMa1lL+1DURLgFO7klkCJ4EY4S+MQA4XsnIb5MH8ruuK7/v13SuQ/LxA==","shasum":"d7e4b44620c7f6137d641bd9afa204b1164ac154","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.0.1-without-cli.tgz","fileCount":37,"unpackedSize":522567,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJe81PRCRA9TVsSAnZWagAAUJ4P+wchBO0koqz6CRhftXRp\nyZz/Z505NFHAyOHoTz+X5kN4bZx/Y7tItZkBZONLzD5CbjwOfx2/EZBZsZbT\nC8AiYOqBtk4gj8kaX39Gn10dTkpKqOJvn5axiEUTgd9IQ3APbcF4wglcYiiQ\nz8suA3XHL9kGDSgkTq62FiDYAV+0yNUzwBJ3GBuyrTh/om1IEvZOJl41B5Ry\n/sV6CPuCOZk5l+rX+JJj8eAX/keAna92Ld2Zht2RSxKxM+aY/ofwsy/YmIHv\nLAv9GgnqMvVJibbluqBPo9hUPDdd+S21phlIvbKh99RqUZecSoNDh/Ksz5Dp\nQtxHeLVaqDW4QwBT7Oq2RcLZNf9bLZRDx8oeZtcUIxTndkMneKjEFxfsIXMc\njgCmpEC56s0rpwvNAuIj+MZ6MGKvGcvjkGF4JDIZwnsVE3Cy1+R06A3QrW+r\nfx4atxVyX+iIqjz8Z3nhoJy2mvgyy/N7+gBQOHZOFiEGYurqsbDbVUHDHYJF\nf1lAQZsCdSuC2pFcY7HcwD4lw5ppeKzvGHkmpegf2/qbvjAzTK/ExTB70Kiq\nvhxkRn+2H3ZS89EkEjPS5x6WUOo+hNXGt6YcbznRxZk7a6/TJt4ZMF5i8RAu\nqKY9M4XsYd21795YxawTLs0WnFZy0QcY0rx057Q1ia1fMGsZbqasWNeMViav\nAgw1\r\n=qmLM\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIAkppGbuNp8gkq0QyG1vzu91k/DGhzumtjHZUYZI3vG3AiEAs+y81hVfV0ICJHnrxl9QpjBsc9a80NxpGIqmwWSFwXk="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.0.1-without-cli_1593005008628_0.5372652046834514"},"_hasShrinkwrap":false},"14.0.2":{"name":"restful-react","version":"14.0.2","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"b890e0c15572f4931919d623a7c1cb9882f40388","_id":"restful-react@14.0.2","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-mktQVuXk5x/1EkK0oLwb2NNaT/qU70J/MRlfDVYFQampOQyGZkS0P2bLFR/LUtmdMUXpll/zm/32LMDGbdZMAw==","shasum":"f1c1a97afb048959407a9de76687ff3417f38a2b","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.0.2.tgz","fileCount":45,"unpackedSize":577253,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJe81qhCRA9TVsSAnZWagAAUasQAIZnE9WUxv8Ns5aYJqXB\n1i4nmMVpo8htVBC7vyolZs/rJ612CO5+cZ+rsIEGSeUV40cYBHfQMK0j9p+N\nZDhQEI3nlhHD+oX+9jyO/L+1VLQ1P6B1Yfe8Ih+nshNOR1RteLkmnrsEvVmW\nkABWhJIkyt3HsYWkTXhBVli5Huw3XPniDgzup17aLqOGmTCxeVc7YGJlc3ji\nI7dRhowoc3O994I5/znDRznHP2wEHzoj8u56UoCSQdW2bBN6ftroggz2PZEY\nWGPk9/ZqyLEXeo+5CNRt8XTgiFXy3m+GqKeMPjbw6k3dfctX0PD+lsCzq2Bi\nm1Ih0W3ryqii6ky70njY2VZ1ip+B3Sp6ikKrPS/nw06GCblR9W9gE720XRlm\nWxXL6+he1JHCzjK4NsntvbldW3EDK81+z4D0fAZUkLE+qy3GevwJrYIrwi/s\nWmearr8iPgLcg6aCCH76a+Xhvp1jdPAx9VVJvPZX4IBeqxJw7hSQ3gNsZSTA\nb/RWDDSu8W1RsUAfkXepH1cRFPqK1zTcM7EkxARy2d768bJY3UdEwtNcUe5n\nThVL7oFa58wMT+9Cs5hnd0y4q2bw0Dh5mJMtLa4fikEKU3Ed8qUxpfuMjIKK\nhiyXntnex1Rtm605drpUx15KgoOSslbrKHmptFUv9bNl3nogiKM1fLzLs6IM\nAheL\r\n=RpmP\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIEAaPENT5Evsf8N2uDd3OBDCIWqMoqeX6EtZAp4/SF/JAiBSq167S9+sjHlhHppLcRqSgbqtrOGyUnginaPRmYw8fQ=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.0.2_1593006752901_0.018804335060359723"},"_hasShrinkwrap":false},"14.0.2-without-cli":{"name":"restful-react","version":"14.0.2-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mocks` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"b890e0c15572f4931919d623a7c1cb9882f40388","_id":"restful-react@14.0.2-without-cli","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-bqCG97Xkmurbi82UD5Yd5zpiQH7t0UrSvEy1ZgLseuUlygMkRiqG17ynoIsPlarZy7dJt/iI3VHLMc6OcCzJOg==","shasum":"2da37b430281c1e44f1dc2afb558dc2562be7ac2","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.0.2-without-cli.tgz","fileCount":37,"unpackedSize":524590,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJe81rLCRA9TVsSAnZWagAAxkAQAJy5+EHkY8mlO5AMcqlg\n18JkEHC8+6IND0O+DT6VwOqfrSvt4tkUFTQto63XOeBqn7BigY7LcPMvXS1N\n+DsS81JSlHfiNWTVSG4PN5hguVahHJUZx9DvfeJ2L5Hq7GchH2k60FE+3h7t\ntGiOhr4Qj5oJAmryD2p54hcDQXXF39JxZ3MemEQfs9bt+gxzxDqv5SVVhbpF\nIqsvlb9+BvCxHkHFwfoMcBhPg3pGgIDVmmCYqkjKlClc+govCRITcbJ+RWj2\nyViLyw0IAeAYooLSWmXyK42SX8+iXCfz9UXvPoli8KJ9A6a9LluxQ2Q/I9tU\nPV+ztJobogm1xw2GB2VyfrxCT5mlnM7ShdvYXd68Zzb73xokpURftbEkHt0l\nrWWVy6Z3PJOrm6Ylm9bO0O0QbcX+5Jde/SBVRiwIqzupu88sh8R5jmX6pu9/\ngMwrOgyQFluRQV4fCj37M+Dry1Z2G2x9iHWtGsbk1kLFpUNX0PXWaFqBJ5Vo\n4yYEp0m0e2YsqMsJ/ACgE+oTu/nkzXCH4gbxGaCcwHLGJ/CdQQCSQWfFcfxc\nhSswQash5XDnyDr3nbgss7iFwbfKcR23UyBy6LCBGWNa9Iuk59Y/E3uT2y4w\n1P/PJPWRUcRd7slrdJP+kRxL4iqbU5/wLRUo4nulY3BRyVT9o/vh8U9uIHS6\noJEr\r\n=OsRn\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIAq+U9hM8LGM9ecaqwFt6Ccsa7FlHEut2cx5xUlZJ9mFAiEAxW8/pQ4kBRNqiPxGJutJTweSgJQzMVFq6ZVemiIGePo="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.0.2-without-cli_1593006794654_0.659918622467923"},"_hasShrinkwrap":false},"14.1.0":{"name":"restful-react","version":"14.1.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"26e106287f731229a616351b4aff0d47d7257371","_id":"restful-react@14.1.0","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-mO7EJg/X/5t13cM4Qh3uVZj6CmJHDIQ/tP1eRkUrNyBU/qzIikls4ZDrC70pGVh2kibY0LL1rP53RSE3oOc1VA==","shasum":"1300c29b06d86334850b2256b4591a1203fbeaa5","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.1.0.tgz","fileCount":45,"unpackedSize":577114,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfBzc+CRA9TVsSAnZWagAACVIP/2FzeOMeX7UWVV6ZPYLS\nJJLkWpa6t48H+f2x43fQOr94bZjZUmBqtQuCyDQIXvB4p4qKb2hs/gj8gfhp\nzv43Vas/Tu2qiTVaqaQG4kzB3lKcEIHPbRab5WILDbJ2JyIJJ7bhh/Sg0ixZ\nm8DOvemIWzddTTImiexVvhuvTJ3enDVUGXMNbE3biEgH9JhSBPYOvQNX1BgB\nSmJVaJ2Lw5bz3Q6LFMyk/cQxJhe60f7P2RKgQAP0sPGQgxNuTzyIFaGf5msl\nxFkqzP9l0D1u3Lx9L0ePM86t/d7wciTS6d0T7zrgag0WISyYRGEfN8XMNxF8\nQwRF2BgTwCMr++WV+iTZ6NfaLpabW+HwcTmju32VyTvZvG9Yc4neS3tVznq9\n9114b3qD5MLYLN+GlDuYqgex6sVBnlp7n5Rm3IY7vsw1T2CyfZ08QMAdWwyK\nt/ygOZpxVjD57txgvNx9YDEczfdpjxPlqCWB8eWffYkijB+zKn9B9qfFnJ+s\nfpnwsqoQsHysM/xkeLZOn1y/TUhTibIjH3aRUqJMKz4YXs0YbcqvWibhlofi\ny2QXjmXidS9XodSBTNkbYRkaYN6mgAWxFy/TovOhKxOmpXJKWZ/q+sO/XtVE\nbwp4vTNbvYB0jJXnN1yzyOoahIZRaffaYzQaT9WPWGFn2GgTmhVfHhA0Less\nG64Q\r\n=ywR8\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCm4mXecJ9PdJ3vYcPEfQH+MtQaAQcbDSWHfFuzuL/s4QIgXhAtnwiM3jYOOgwmdkHoNBOsmkh8H9bnUWPIbRslMcA="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.1.0_1594308414365_0.5793625065062509"},"_hasShrinkwrap":false},"14.1.1":{"name":"restful-react","version":"14.1.1","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0","yamljs":"^0.3.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"5e1b7d16ef04d37a8a95a65ed2ced313dd96db2e","_id":"restful-react@14.1.1","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-7aIj09ilOs0DtAxO+Cieq3gNYRArE28CMdKrAOOKg1hs8bErS/kiDKtYwCDOsFl4eYO1UK56n8lBzXK/2VMRfQ==","shasum":"d253469438b4fa34fb419eb22e5f2fd225dfd145","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.1.1.tgz","fileCount":45,"unpackedSize":577544,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfBzlRCRA9TVsSAnZWagAAHkEQAJ0GqwzFqdFSpUGepYl8\nNQSW+F2giR6/D/JSa4/jDkHceGMz6kTd2RvZl9JyBJM+BfDUB1VHB5gNFpzU\n7sdx6QOpHD492h8RRkiej3+ls8vCpUZQ5BJ/yCdQ/9T7J+LRYuQ3ChvhoEgl\nkADG8VqGQ5lfM7/QeV3SbtyGBHUByIKRi+O8L4/f9NkVl7LroRxUzSKwm+ju\nUE6QdIGhxPoz+nvtQPoHnzL2rkyGZpXHD1zGyP1CvxIhXhfsspjcVgCN9PDf\nbskt+7VXcZJJFW1wEMVmLS+UtWrRamXui66PPLRVqzgSXi7wY2LfPqgbOOvj\n7vV3SQUxzsEktGSnuyWMic0F8jZrTHfFBACP1I912HsMonJrGVgjlV3DH5Lq\n1GNjdo9MF/2BktcyGzIISuy87EVxoO04d0wU+eYN9xJhWldQlTV3TQXMMKqx\nolkNEI8FIEuEjOes6VNaRajBRYm4JG7WexxWaFL6GbdQp40GxQeaDWCwSgFP\napC2vpV11g4/2g4iyTQ4y0zACAt3mk6/9QY/Jg6yudkdXxIL/I4sLCfK++EB\n12vtGV2DCgzTc11YwbcOEhRSs4Ag0Su4CrhMcrZNigG5EIMzmm1AFkxHCi4N\npT9FuRHKHeLsd7MF+wTXuIaWo0sjfBfIq5Y24xuYdBCyXZL12ZKFNKF1Pot9\nOVyB\r\n=dy+6\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDRoC6CbPHNoyHCCV2/rtxXY+zCAB16BWCqdGMhMUmq4QIhAItsqSNrRDfn8q3etqHIUHToKhegfZaC2m2Q5IbE0Lql"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.1.1_1594308945039_0.9946559248449167"},"_hasShrinkwrap":false},"14.1.1-without-cli":{"name":"restful-react","version":"14.1.1-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mocks` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"5e1b7d16ef04d37a8a95a65ed2ced313dd96db2e","_id":"restful-react@14.1.1-without-cli","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-lKOmWW1FMWKxdkBi8KWPLgjWi6BUmr590Z1dolTDXO8FcoDIfAVEbI7m5Jc17lfKs6OdnSPWoWEVesuHF5ZN6w==","shasum":"c142e12123180e44bbc7eba63f394afd2bcca8bc","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.1.1-without-cli.tgz","fileCount":37,"unpackedSize":524798,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfBzlnCRA9TVsSAnZWagAA67QP/3xxX+sXTzCGMeokQliO\nwAXXhBlpXfTnL92zIiMm4aIxVZ+P5fQ6mqmxeCE9Qfv09m6+cGeJ7Expup3L\nXKrVQfcUSwiIV5h6lzW8Ub7D0IXiBsb4vCCB0vCyieUyM/++yUVo+wgHNqak\nEP3S6eI6kKrndptFSq5KuU3w57a7o41/CDJINqY9bDHGZzQmfWyAwfhoOQvl\nWqTGovbVwHljQY3hEp9yLrXVnC9sauPk4Ki9JwCz9Y95JAKdX9ZnFV9Kqidy\nceFUlGz6ZfoFHYaHVHKmDEm78MXXf6LbIuiBEV/qS2FtbI8iDilqH4ltg/OV\neSiJZS1MLT34BQ40kRhuxAx0a1URq/Y4StE8VMP/wPPzIM3LBwdRxJmNVxvk\nAz1GDYdtyF5xDk8K6DmtKaNSo8PyVY37bAOcOgPgS+gwppNwbPYouK9ylFmP\n1USwrYX9bQQ5un6uH+EhosFkez+FrQM+m593QVMAR2GLp+Fc6y+AKNQ4vdiu\nbmW/1dla/Ob0h4rrJ1UJtnH2qqsa424BpKlhc5iyNnZlZTfmtai0EmDCRcql\nz2L5iYsKNDslUiaqNm8xAIV1dRoh6b+AiQIxCFHrJi7JII1BUqQHDOuSiICw\nkwEYfrm0ygUlGwrHPM8y9y/9+8C3HwE+mi+EWo+63LrEX96my1+DPZLMYmrZ\nY8Tt\r\n=PldK\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICC0VtPJdz27btCB0tHHIFzNyqEtPuzrt14ed0+NAge/AiEAsz+VmeOTzTXcmk9MUzw+UJE0YfmIFTqXZ5k8GXR6QG4="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.1.1-without-cli_1594308967496_0.647913363887594"},"_hasShrinkwrap":false},"14.2.0":{"name":"restful-react","version":"14.2.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"88a0a22ac0824a20fbcabde9ecf91e2463aec30d","_id":"restful-react@14.2.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-MTA2u0UhmY9MlvcjQvVhuwHBuF3EotueR7lMliOqIBhHh2gE1vWcqP29XxvDpXv/ypWCwN7Yrjqyf8KiqlqU4g==","shasum":"4e4e3dbdf3c0b5f49e83f2c45c97810e8a16e964","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.2.0.tgz","fileCount":57,"unpackedSize":579364,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfCDNUCRA9TVsSAnZWagAAL98QAIsv7xMqxptwSXYAMb7g\nd57jJ9stwxHB0Hd3xn3SAi4BRLnwoA7aqz/8fGN8ikJYXbF2GHCP+ssQ6Y7d\nppPps/ELRS4sNI8MUok8b26HLAzEMLubPW73VlSNkKJnUmaYWfxhP4vNFkgx\nvxVmxvM/YNkJF/xzNS1S4mfPM4Hilksd3iGE5BeRZcxEX6U9nB5iUBy6E6Sr\nztZtFHvsM+DxRJzPFYJCMGyFCBpakSX08tk5/3Sn5oJGJB8sziH9zlwl1S7O\n4cwal9I6N6ZYJ8qVkjuMMqwFFyyi1pPrzqAuRxgMpNFcyJ+wm3qQwClkOTvw\nCSb4Aza+VgojZ+Ewal3SljzlJ3xDgz7x1RRsR5uISQab3tmWTefVsjYCTY/o\nNbb3fbqtpoVR2RhFnfqioK4Ej5tM9kf7U5ekJuopDPMCRTwmylwrkB3Yogyc\najFf7AkUWD79PEA9GqbJisup2oDOwKh68tVOLvgc1RvzXmG4ysxrTX96QE7J\nS0XL2/JXef0ZekYFcrmiGn1ZkV40OytA5+X25GH9JW57gOD7Wrn9AHXi8Plf\nqKszt6+aetNI32fUqPkcnhd42ayAHwfyHI7ktIjOdsexo1A2tP0xoQzfwOGy\nU/jxNsuIQa+CjGVUoaNKVw++aOA47X2Y69v5Wnun0PLoNTlOdvOraOoeSMPg\nsnpp\r\n=+ESM\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCj0CtRID2B7cxS0sULn772f9KNXdFppjBqTv5GHe6KrgIhALiCpSBpye7bKoOr2DJ+37hQ7vTjpikTHMkUY89Eno8X"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.2.0_1594372947989_0.43639545940061875"},"_hasShrinkwrap":false},"14.2.0-without-cli":{"name":"restful-react","version":"14.2.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mocks` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"88a0a22ac0824a20fbcabde9ecf91e2463aec30d","_id":"restful-react@14.2.0-without-cli","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-x9CBNah+brpU85+qg6p0hh0+yUkwiObpzcSWtrOZERVesWuoTiG4uAitGi4NJFWVwG8vzFvHvPJ6ZbJUagY8XQ==","shasum":"6a1b20db17cf8e06869f223d02f4c221f9576612","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.2.0-without-cli.tgz","fileCount":37,"unpackedSize":525900,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfCDUNCRA9TVsSAnZWagAA9LEP/16H7W/pcvPZe84FalG5\nZv5zbR6UHczBCH4nPgZJBxl7+12BUBh/0cYyWM2HQ5gtL0+9d3gcNr1UDAaz\nnVMjxgVuhhA9u4j9f9xAesJGQ6hoR5D6Bxbm+oVTgMu2+w/npxfh9FtBO0ZC\nVnOg4CaXNTibADqrxV/7bW35GGAJ2VemZ2Di/WgdnS3Bku31KTQ7E1Zg8//z\nkZCCjsJi0jAwzrQWs0dx5i0MYUpACWOamSOOWWSnGWABLTQggaNzsRPd8imx\ntys5ALq+AWxa8erKukkz0TEJC3VE0H9V5f6bgAC/WJhJvgz/BIKK5qADVpnk\nnOLhtYoiwpUBAvN1RW8jmtTX59DJzIVxMCqV9zu3ER70RnH/Yq/eKwXcaSKO\nwfhvYKY23ubM5tnHzj8FY0UNUWRTiNIwnqZI9inzepqsnjyO6lmZFxo/qaqw\nNoGUVK79eal3Q+nLirHU+Th8TGnS84hQX545ZHz3ktePvhb2UGm38GDRHCVz\nggGsbegh2IcbtBQTR2Nrj0OmnMkRdmQGPGO8CUEWwUamatDb1LOfnJwEGEKs\nbHeVDeSTgICfPTACDyxf2SVzoLjF+ygf+1GmA7cfh3E1blC3D2a3JwDogfHf\nTA+33a6wCTW+MwKykpXlQSWFSbPpw+NVKvrSI9GAXP42QSP7iFAS3ZNaUxZj\nvfIG\r\n=jyBZ\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIF+Kr2p3DzcjiINfx4zR9f6OrQoLZG3D+WeCrhbVCXrFAiAUybKytirVOlQDA1bsPxDsLNgyz6NravrCFXTGQ5FjqQ=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.2.0-without-cli_1594373388664_0.6766037087047931"},"_hasShrinkwrap":false},"14.2.1":{"name":"restful-react","version":"14.2.1","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"d18b13c3629006127090cdcecaecd448f3310a35","_id":"restful-react@14.2.1","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-JFcWnt8blFuwYcqP1x9STN5lZ5L+VAUPPuUW1UUFJdRwbrs1LbhNziV20fQWhcpREzvrJgvzuVuXd6tfOYfhcw==","shasum":"a4f32b44435c7facf8c5cba8b352b5b886e12930","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.2.1.tgz","fileCount":57,"unpackedSize":579789,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfCFbVCRA9TVsSAnZWagAAMlwP/joMHadccoLtwpWcciSg\nuX0nTVWMkixq0Xcu5w51Huba7amSwylI6wXwcj166htBJZAyTtISl8nTGQ6o\nYfDoMmy9JSUYXvxEquxTlY/b9+SCpXsuadV766Y0XN0sEdsCMMYL+sXy+Z3O\n9zLykJYvHLS8y/b51X/U7X77B8mTFSJ2Qt18mtym64etETGfi5vnZHoSZIWu\nmbAgpgH/Wj1kQdHeYfSMiR6AirMaEPmUGSouLtu6zivz6Zv6rDHK0EwDnxfa\nCK6gU0eKIZRKug/DD0Rj7OAhGyRXz3HLFqrfkLiuSbb3+DIqVZNqsBUClqRt\nPhjrBW8dpfObsPPPkchFgJaPXn1pm039WfrOh/3q5twA81yEl7oeongGcD1l\nGsoZ8Gw8JeNQtKyCZ1/5Ile4EuSE06GQBsbcbZhyAL4Ltaiw/4IJdFO49UiE\ncFfKNNLEumrdXuUFfDEct5dZLk1fcsVIlvaF0LTlw+xivz84I0OaB0/1PMPo\nvJKZ9NDILAuaQZGROAv2bbxN+V/Gq25QuWlwb7ZLqRIASjya8uhJrgv9oK2M\nI43nGGAsbYQOs84hYOzyhbu7Bvr8WLX7s9moHnzt637wyI5y8XiSHg3lT3im\nfH0H5c34fBYXmO2Un7nObnKNSvhfzEtrcbR1CEmOzjb+/vjmLXSPAT6zIt9x\n6l1h\r\n=YIk0\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCaPp4+1ljFlqOJZj4ZIBsBNx7OsGPVuXJM7cbargB+KgIgZ/Ytf0M2O5Sbw2WakriBXPiwtjzEC3M/u0dxCIdM53E="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.2.1_1594382036399_0.016531671392935543"},"_hasShrinkwrap":false},"14.2.1-without-cli":{"name":"restful-react","version":"14.2.1-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"d18b13c3629006127090cdcecaecd448f3310a35","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mocks` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@14.2.1-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-X5OaGEqa0ssyawNaSLb8n+RSizbMU15mRz1SXaB/EWd9MorCFkG4VjOtKj4jjKs5EcQWcMmKyLsg8j/tSH1ikA==","shasum":"0faf29874653d889c2fde9fe82f7260564bb3c96","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.2.1-without-cli.tgz","fileCount":47,"unpackedSize":527539,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfCFblCRA9TVsSAnZWagAA6OcP+QEzjJMb4oYNUUsrYk/0\nPP5VBrY6A9u8qJdex55E35nvRX+tWc77jAj5yPO3sR/YMkc4xGxIERseEpkH\noazXaj2qAVJ02MD5GYoobXXMwqa24cGosNebeueM8WQUvXhzp7Bi6rIdmCBj\nDifEnbTvWiPsm5+B/DZDZvZvKIE0Xcx3J292fMJdHcM7P9I4ZUjAHJKB20F3\n5CRkJsOzmHS4ciwbynl06sSB92nXROnrs9EAgaToSzHxp3vDqgs7ie/dnYD9\nX2/n6RTEBld2adu95WH7bpVKPGcH9CNFtQ6O5fQUe0gh+XQ7cqHLLS0buyu1\nslFCCCmuqNYwda8zLSD+grgY2hVKBDmm6ESje5u5VMF8qxnRkdhZY8XQ0wnW\ncfj3Miz/IwZEh7O3Tnh+USUqlfkZbsgRnTENTXSKG/GH1NK2DMJnwdg1spuM\n0N4MPUi+U3THKJa4Qx/FFvUMW3P4Xg6Tp2ptOomLiEJsVwuSiejXcPy5vFA5\nASnlm+Tw2XQ/swaKvHhHvLMYiSke7KcBcqeIuI7yqcB0CD+TSjyf84QXhoPD\n8pDD9+3slPL97sQBBrOH3fhSzGQdIV88JWH/0PnbagcTTgm60whaxMhQ8uGO\nYq7XjbLEFYGhjQkqNpZtY8yYzOXNcXhtmZ5tf1cKe7uHINd19sqcvP/zYd4K\nqKEF\r\n=vEVc\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCXrP1T75GEycIxyA4XqQMi+QbkxTGQtKIjN12ktMxm9AIgcRqu/23sBDfhgoVGkyp2wFY9utP63yKMDEI6opsD4SQ="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.2.1-without-cli_1594382052840_0.9340416082151193"},"_hasShrinkwrap":false},"14.3.0-without-cli":{"name":"restful-react","version":"14.3.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"454db37e029fdd3b8fceb98a6dc977720a91cb0b","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mocks` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@14.3.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-O969PrOO6IQe2ktThKGgC9sgrl1puPUmaVC7ncjR6KkqoceLS4Q58iJD1sq8OMgfE71vTFlCgdwHqaXHrxaUyw==","shasum":"6edf003201c8f22d37f03120891a673f23ac7ee5","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.3.0-without-cli.tgz","fileCount":47,"unpackedSize":531088,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfFZmXCRA9TVsSAnZWagAAzEQQAJbbNInqcNFMq0BESsL1\nqo8OF6bqv00tP18WPPgutsdfiZ7vd15trQ9wD0ZIpQEblh9Z8wQhgyfmOuq5\n2FLnC/vLTfabQONMvoqdsevmtrgTnxaLF6OoOPZHbg8GxMjQhJ++vwLm0Rc/\n89ASQ2I45BBmbYbrf/SowlSpf9nFbv83WmsimAZqOxSj5J+GBfigGteCfZOC\n1L0LmYxNBNbXpQZdM8q789XZ+Y0EZ0SxAqgMyQCDTbJwbEwZDh5dPbeKbK8p\nQ9NwzPsyRRwC8UFL15JuAKLRavYce+iZYIbVpmmT/7xri02R7SD3QVid1SpD\nOtt+oQPi+OldDLysdx6DbjSCm+pUtSfIjCDwxcmdbCGkW2diOx1l0uv1Gd0B\naiSFgLO/cqSaBl0nf8oSbYPk5u/VoXLHKmTvA4vVCHdF2QUfkEOOHsInndQv\nk/6tD4IlpI4+NRHaq5ASGEsGprSMD8M5WZtwsD45EChrgYluIZtn18QspFgL\nY7hpmHYUIV31qAiuCFf0S+W2AETzz56pvCl7bwAzsZyoFlfMK3gtO+Fpt/aR\nstrlDraWGh1qAV7VWwpCg6ro2RwW/isv+2wLtNrxvoWFkRdwd2MAUcbUIMmS\nM97H1lPoTfLARzioPox9VkvBk5Ucvf1ND6/x+bgjiJ1rBJNA5MP+v9XXovGl\na5nC\r\n=yR01\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCq21Igvj2kWZoyBfaYbJOj0EoeKOtoB1q18xNXA6UjWgIhAK/ekwnk1hL27frnYuA5r7ldGikcQdgGvgdG53hyIKR+"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.3.0-without-cli_1595251094764_0.19753850924277594"},"_hasShrinkwrap":false},"14.3.0":{"name":"restful-react","version":"14.3.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"454db37e029fdd3b8fceb98a6dc977720a91cb0b","_id":"restful-react@14.3.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-C14M5vjWv3zRWznZ+MarneN9VvChMKW1aM7kWn4AtK+e7WW1tTbu6PcQXD5XFUDaxNqKuKlwBgNOkn+iLCR7OA==","shasum":"4914bee4f08cf21dcda0d21c30e7194c4b9d0a67","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.3.0.tgz","fileCount":57,"unpackedSize":583338,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfFZmpCRA9TVsSAnZWagAAiogP/0JyAV58mF2BLh/Bhyac\n8ZByvC+XC9+Jrm/dOzNndkEEMwQXsb46v5wSsOWSoNNJ1f5vMtzZwIyuu6ew\nAN3y4aoBPXonTmViN6ohSEJOe3clNBgDYHThWnSg3CGQLQaZiQtXP95aF83g\noG3gbWwrDqUU+KiBCl5WkHLjbSnfkR0HimTSTzFp81S0OTRXLuTW38EJayhs\n2TlC/H5+i4BZEHKKYynjj11J/LZdma72n1NcJdDLdjmTb5K8sIKHsW8GEJvs\nsGJtjlZzzolr+hoLtYY+oH80tHq8z98BKpSgbxAMzyHBtlIttxWOivvTAyJd\n8G3CNp2qldXFj3fBiTSUkrsGPmsS01QBsEqQXJnh1NV/H0x133kIXiGJ6dI3\n3foTYiEVocTagt5F1oa5D8SuvK7W10FVgsaAqxuFX8lIb8jbRJInGi1K66qZ\nzyk0AkqICpLdfVWGuJIGLbJ/AMbDGmosA3kTZjqUMVeOLTf19+xLXBWKrpcJ\nvY8og8xo1Y0cRPzJEOIkcQ4UsjZ5mu7u0UsIibWqhuQjJ1vAT0t0alPqyMuB\n/v+YMyYB+LemWR+k9mwM1cISNU1tl17JICGV7GaZNjY88919Vehh8s4g1l/Z\nT9QFeUfBIaFVDOGb2mxMLPhX67IEjG3sEw12HYc03b0J6k62e9yISr0J37dm\nCxFw\r\n=hfTJ\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIAQ57K0lZ09aeu5rP1vbbeUIvdFJBk45BLW4YU9dPdfzAiEAqUHOtSthf5lkiZyK5A19u9HgdrU+6lZUKRWK0Iltw1Y="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.3.0_1595251112427_0.9703593939152666"},"_hasShrinkwrap":false},"14.4.0":{"name":"restful-react","version":"14.4.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"5c3bf6684a1a5a589c7ea0975804edae299c8b8a","_id":"restful-react@14.4.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-Hm1aHvuJ6wH5R6ihn/uPC6orrDnup0ldQGi4MOFN01d28Xe2d+IyKeg7unRC5mDROO+o3p/uTZJuCz/kHDFmeg==","shasum":"0d44115a97b546436b8a5eee349b11956723a12d","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.4.0.tgz","fileCount":57,"unpackedSize":584151,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfMn0NCRA9TVsSAnZWagAAyIcP/AtPzZi7klM8nThZm6ee\n7L92pqEqEGbUoVBy4rNr4PH6+ysN0viAxszR8CGzDuj3KixSh+sxgsCk+xZV\nyAqfrPbD0+vu1Spx5pErfFVTLLOIUSu9i5b5k9xip9NJW4hyfgY72gWW28z9\nIjYH2PgJARwGukjTfZ98fLgu060cNSZ2qIy2fzZkw0upeqyOs8WEn1m+8mjq\nrHXqaxNhYFoaEBELi+HPkAaNNrUBl2p7dkqUTKZGsUmaO3jc+nYqffrvmcp5\n/YFYh9/dLcYQ251tB1HKc2qfdrqn+a61ob7jl+75o47AvXLKNYZ4YoyMfoeW\nUrxfH+O64tdY+TpZ7fHsdrwiXT1ZabOeAmLCHaoa4tvFHKTZmHJwlKUGSB56\noHRtN7x5bBGC49zNkW7/Rz7JGis63oVMw4MAuUpVn+5g6OMy45ytcP763C9L\nqrG7O3obyufr2R45HF/popyC+JTzcx6qcDUjfibfiyV1RvViQ5rRfbunerah\ncRpffbF810rbxVwx6e79matqEUGBQ3OfqOYHQSBTXd9D+7KQh2Jd8fPqWSaQ\n0Jw5fAiznHHbPpmoSRrvVO1kLOesKK/BVIiUijNQWrcfJrDooJI7vcpePi9k\nQqDIHsWRnB+6OaErm6HOQCxXlT9lm+mFm9uxVdMvw0ma6q2ACI+p6kff6jyy\nv8p/\r\n=nMan\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICxAcTG5uAdX5qsrmM9nZNnVEtGy46h+REsH9m6xzFPXAiAYhu4r5wOFvVAxrA7ocdwcf3W4sM/GBKVeDsu+u1B+hA=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.4.0_1597144332461_0.40710310552859386"},"_hasShrinkwrap":false},"14.4.0-without-cli":{"name":"restful-react","version":"14.4.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"5c3bf6684a1a5a589c7ea0975804edae299c8b8a","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: (() => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={authToken => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mocks` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@14.4.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-ILyH3zLCmZgHJTS0yrLpSRG5qRU3ZzUJwHlSyrj0tw7tObbso/bLDtguG9q4kjMe72ZoBiTx/DQFF+iR6txeHQ==","shasum":"8f0e099336160d169560274c8db4e8b445872a87","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.4.0-without-cli.tgz","fileCount":47,"unpackedSize":531901,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfMn0dCRA9TVsSAnZWagAAMnEQAI3aT/FA9l1GTiaf1dBT\nY21iiadZesf+SUQsDxVMVvlgxZz4c0UhWu9fCRUB7t8HgthdsJACaqgWg1Rj\nAR146WS8VHtxVqDJ3HUN/aMY/oaRhmaUEjojc1+gU2Ahi78fqufC+DzzczXR\ndS6tzIR4MJc1kyTAgxXWbBZjP8VlCvJ1rBL2y/NnJv1VhJtIp9xPWGPmPp+E\nTATlpbrOne+goH0NHYSVjuIchU5uPGag65dQIgkipEzcCI+N2P+nmVZQApsr\na4Gh0fifh1kIvfBPzxsXWc/IwNdyEYDixTXF/9jInyCEk3JXa4d+whxuVuiS\nfFB6/qz1TJLWE2Ca8qWyTi+64FkW7EhghHWdebYPV+57RGMEVDq27md9me8/\nO7+QnHz3xp7W7n9mADtrOpDzkuZTI/U7b7Yl8vr3HbaSAEnVyM7zO2wO1Jca\n7ZIAwypM75xtwohynFxrdaLA2La2lc6HszyYxJ/KLl/Y9ZjvZfwDbNbCUrjq\nl1rn0uBa82IUHnt25YKf8wDPwxpPuLXR5elElHkidLAWSq9b39c1idqJfOcj\n2Z6LirBmNb+5dcS7JRtb/Q4KlfYiBOMPaqg8BwEMm+RUvLaoA5B9jDwsMYTM\ncCHUyAISYYWXKYSkP6bHPCNM2GYqFrXpC3eH8oATy+AsIqKpowIj0biQZdZH\nz0WH\r\n=EvTq\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIHD1r5fbqnR0bbAos72uSLdm78WhOYN7rBBZljdHfMVUAiA8vt+J/hZMG9sy9sPnN+o50gzW7ohPJMdxC1SwLDgYSA=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.4.0-without-cli_1597144348775_0.012528559113442528"},"_hasShrinkwrap":false},"14.5.0-without-cli":{"name":"restful-react","version":"14.5.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"0bd68669d2050e9a3cc63946dbae3ae1544e1d02","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mocks` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mocks: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@14.5.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-VjExIIzpmEf4qvcHK//36QZ9RJq24TH6JQ5iKda5/btxhed56N3RxYxnjSsiYFw/cf/bNmY3hR7lvXzdnOiURQ==","shasum":"4e93299c2f0e2247aeab3232d4cc19b65fa0ac9b","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.5.0-without-cli.tgz","fileCount":49,"unpackedSize":545915,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfThZlCRA9TVsSAnZWagAABUgP/RCeEG8S9zWTn7gPxtUm\n/mBC+/Y7aUs6Yek3uYD6aMA+hFK95f0LWTy2mWD6/4ZtaTDz1kSgMJI8Ogo2\nyvdjBAKfscTYkp2fG0yd+70/+62kbvBdutYGT0HHjWPQ/XtHjqw6TkWmV5mj\n0YXV7uQFBAhnqsKrBp3lMZqOcWEgQAQM3ZRnD3UpqyyLgybrILWSTLEY/vHQ\nLkvO765kA6XvOhRKsnbpxaoHHMcxZbP9byO3VZQhiesbNnYqBN5pQ9re3uS5\nXZ8bJ2ckDG1xabT2sJIEjGChbn1lzvZC4ZSGMok8LdqXVnIQEtWfI1ZwoWz8\nIleTTiP6eeQ/SYYGqbFsGce9RTYnG6VMlr/bZpkrYQZf3+Rk0Ji1oH/+K3wd\nEJv+GBiATyDyK3a2hUWKrgdJltpw+lkfQmU69DAqxflyKOBRS8CQgFel3lEi\n6zx7VnR0GEi6ehi3cDQLbOsLQZ8VwCqgGS4/iRxmdSAVbNnnWUilMNspNRmI\nzxWrKsmdKN/alpR7ZpavM1OT0ZjOQZXAeMFZnATBvdH4KWvrIIXOQZ17eKfz\n/4r3hiaBLa+TloXpvH4pBTMELjboqfw9Ia5QiFRJMbt8wafINasQjFqVeszW\ntV0QGHWR2VUj2F70JoVhyi2ARODUs1x2zuzFdMB7AWDfkZFGsKzPknu503ij\nyYW1\r\n=yfkP\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIBxr5kB4/Q3Sr5kK1KIijbAljFH/4s83aMkF9ZOxFYldAiAaZREUoe5CNrKRbP4HGp/6SemdBLTVtpSKqEuLd+JZmw=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.5.0-without-cli_1598953060747_0.9059955522276826"},"_hasShrinkwrap":false},"14.5.0":{"name":"restful-react","version":"14.5.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"0bd68669d2050e9a3cc63946dbae3ae1544e1d02","_id":"restful-react@14.5.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-XnETZi9+D7Pnz1BPyQn2fPS+0EWSOJeYVhFWDlsteh6vBYXFg+sP9s2kuGpW+JMOicedHzp4wuw+ZGPR96HPVQ==","shasum":"2bcf5e166d223c85c02d7f3876185063351d36df","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.5.0.tgz","fileCount":59,"unpackedSize":600037,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfThZ8CRA9TVsSAnZWagAAz1wP+gOsqstadO30A3iQXPFi\nduzO/maaLyLUOHSivmqoUJXDxlUjAC2ibgbgsR5ND9Gx9w6bi3iSFcZgO4Q8\noFVwe9wi9BmZX5N3vRIg8plP9Xrw90TJMl8WaxjtPMnBZqmV1JNYMFyOmIh1\nmCvLGTUNxd3xlNiePxVEqR5EUgnmmkO8XeHv2wPs1OuUL6drKWNiGMLu/pWC\nWabxtpRMRHzQm5/V+a6dMPlArF+ublzTBEyRRImjToC24cVi+9SPJWXBdrEx\nd3BvEQ3svPuM+LSTAQLTZ95oEkT5haW2p6+HwdJ6EEpQKiR0VHbh8bGtKvR2\nupjBu0mytUmX2x3BWABytBlbio0NlG5YuvlcmlyBTDR9bdrLqhbygedEramM\nn2HxkCAdCPkME2pZCVMrIeU+Ka/2C+XY7bJTk02C0vKKoDqnOWJQwVGA2mS3\nZGWAu8sztjC0RY+Ow3mvLX57DxRHJWSGh3EZmioNUJTOR2KLBqsLXeVk26zw\nPUOsu+VSV19l/sUUsIi3dfzn3MJU/pyj+sD4kOnYytNuAj8LlnhF92CwyEYF\naddcHcKPxEcQEvBVwOHN2ryYocd1sISdmmL3Uxf4OXWzIn/NRMzA2UVW7tuK\ni1qLRE13HSNeBZ+lRBdFHRssisLI026xc+5UywQZWomPtl//fpyg7ZjHicbO\nL3Hd\r\n=RyBr\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIGGBADnzkgU6wYjosyUYS0zyfrG+8Yj1DwDVhNUZ7TPjAiACDRaWFjseESkTmad/rfdFi/pLkCszr7b2ueCEw+jfIw=="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.5.0_1598953083324_0.740967650385542"},"_hasShrinkwrap":false},"14.5.1":{"name":"restful-react","version":"14.5.1","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"d8f583db002f1abdfb77d2f8991d77d6a824ba86","_id":"restful-react@14.5.1","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-BOJPFQjq5hUf/6redctuvGcMr19SDfZ7wPobW3CknDcyNXMwMg8EUd/T63kQvU073Xh5cuTRAS1GgNj3YGnQyg==","shasum":"5ed290e53b7af3927508277da2dbe1f106a86e0b","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.5.1.tgz","fileCount":59,"unpackedSize":600041,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfThegCRA9TVsSAnZWagAAQ+IP/2i3JD26vFon4555lvuR\nHoCe/JJjgyUnsqyEHxzMbzCNI00K9qmhqD959/DsZ/Qzu+eZyUGFo1phL3Rp\nWREqszLtQEAEviS4AY1uUvlm/HJi3DU06BULrYymqIv46wze5dAykbE7NxZW\n3ZOw27ZCBp3jp1livmU1Znjmd6bQmKBxSVGAvGOMfUI8yo4yl9+s6z1nrrTp\nhw3x20mgU8+tZXs8LhT4nLMcamDKMzs8apNgFguoQpWRCSvXzFwYOLsgeRmt\n9RYa8HIOH2cJqNXmOsaHW3CAC4dFEarJ9UQ79PGwsANZWiFDdR+Vv5MjdEiV\npRGe8ym01/zMpJPPOAKsIItCyAzyR4V5e9afYIb8i8iCOUy0omq8v2Z0MuLK\nUtTGGEAtIOLYeasf3mz9GmpzgRpCLgOxmolsOfZ/bsbalKYfUs875rU7PT73\n/zccG/o1XZn271u+pKhokdGb1cZXGF3CJVBeaN4FEFMKh/qqVeC6TTOupZrU\n4dOer1LoC3b2teOiRA9EGkFX5prJgwW4Dnc4grBg9K/8OpZyuhh94LvdQFvY\nRJNNyBjrkIDoLNHTzM9X4GcdrFS6Ei3J3g1YmdqxaKXq/pbjRVzhG/DBIvQu\n9lpYy8uObGvr462S8N6CGHAaS6O97cGDUWvG/gcLnZNBxDpymRf3dOiqYTr6\nUm3p\r\n=bESC\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIDdKq/MgqYyN9unTq61qQPMSeSUGQeC2xhzt/yNsSxYLAiEAxU7tj5qi+CHGcBhY7Idr6k0VoCEVDd3oRofgpOeYjpA="}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.5.1_1598953376386_0.23221595569344933"},"_hasShrinkwrap":false},"14.5.1-without-cli":{"name":"restful-react","version":"14.5.1-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"gitHead":"d8f583db002f1abdfb77d2f8991d77d6a824ba86","readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications. It can be considered a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.\n\nAs an abstraction, this tool allows for greater consistency and maintainability of dynamic codebases.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","_id":"restful-react@14.5.1-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-iW6dR1DhuConBz10nVKc3uvnNC2nOK3M1ugymIAwZa8wIVQB+kyUYgzdGyiJfrLEjxnpqeXAzlfuPTnPPZVsfg==","shasum":"0572fc839a6e0db9c7a4380f0efbe1dedac2eac1","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-14.5.1-without-cli.tgz","fileCount":49,"unpackedSize":545911,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfThenCRA9TVsSAnZWagAAKDgP/2N0ZDdk7K8hV2uMoDVP\nRdI6kKikrVfyW/EnfJlY07uJTvgmCp7jWk9bsdZq7cS0mW4PyBViybLCrMKT\nuzOoxyPfNZCjVTWKehLZ4eGlnU5d3TCWmmTsGcV2GSAMa/PQ5JCjuqJHpP2i\n/9BB3Il4wUtRgqf2P5X0DaDznslZHygAg0BCmhH0CFwJjkLV1F0g+GXU6BtZ\nC/tIPDVFxMMYxOJlLEea7i3iIrhEQONjmOmIFhWQ6ayHSx3Z1MEQfMFwqy+5\n449mVuMMwSaQfpc4P3UlJ7Cuz3Pz8gjQrXmHzggl1/67Rqw1/r1MU8Mv21fb\nhgkVd0k0F2Q8u4Dp4U7KN3mpkTgN1nIbvX5AjoCdzIbjXTXMsxdlP2nOXU7P\no1hvQjSfwFUbFO1ZtM9CxEaIoKaTFzSItx5VTMVKi0SE0GNSHzbXPkinCrf0\neUcRiImkxGevxq6QI8BmEsUswF9FWH6bdEHeOHpsHtjm3PHh2ncF1rCf4u+e\nXO5FZ9KbqdcD9sMec79hpXdm45UBQBC5EcWxAgCZW4Bjn/t2eB7gaAtMq4dU\nkXAr6Lnvg4p7vSM8pLitoLlTdN3cXlTPO9DYhwh9/IwxaIv9Nw9Qi8ESBUVJ\nZSNIhNrbDXFpUD2YlGQhU1FeltD9rDKbRj01D4XBDk6qFSjJoOs0LCF0+Iab\nAD1l\r\n=WuMV\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDOPVZWbUyBHkhAeszVPUExlAvtNt+XiOsQUoh1syBRqwIhAL3GO8ZlfLlPai40FauMlLXbuvigPVABEjQZ+6R+/tff"}]},"maintainers":[{"name":"tejaskumar","email":"tejas@tejas.qa"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_14.5.1-without-cli_1598953383298_0.0028214980209464446"},"_hasShrinkwrap":false},"15.0.0-alpha":{"name":"restful-react","version":"15.0.0-alpha","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"90bd7f9d33467bc2f2c89180fc1d8efa6cba6ee0","_id":"restful-react@15.0.0-alpha","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-l0BMR2XsqBf7MuhYbU8oaB2Oroirrmm+de+sRIeZU+eCbD0gv0a1ygICViCu+QL1MgzCayYh4QITazGNnpEClg==","shasum":"b4f34415c4f10e24fe511e5466d7815f0bd4be5f","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.0.0-alpha.tgz","fileCount":47,"unpackedSize":599638,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfc1bwCRA9TVsSAnZWagAAb0oP/2NRIy9rlvNPn1FCCDMB\n1viD/WxyT/5iwYFCeWudecIlVXoUIOzfpkTBw60GFo2SD3Ft29YoRWjViaLS\ngdyx+vD0oECMsorgIuXkOG0oCKJa3hOdfkOgZ6FuRkTG4wkJZLrUrQFcc+mv\nSZ4TY2rOpBJLJZxlhvl+QLieoxxIwy0O0kcRuG9Ovp0fCOY/7HsPj1LpIO82\nNeH/REhJu3hlgkZEmyZ0Advi0645A+9pjd9LA8DEBFLirdirt7IdXPJtmjNm\nV9JbwL8mS55EeVrRRMbbB6JkoLuoPoPtiXPAhJRWiKvY/O8od3rKRKr00fxr\nNMjpm1TekBMqRYSUg0I3AWbBRsaleRCm58kPi4OuXwwt/+25lWEVr3dZ2EI3\nZKLAEe0t/ChQ895pmoqJvDhhuhPr1i+5RBcoxrJqkCiN54ZjS23gvOmI30at\n1sQWvMLSQhmiJNVbq3Y8G949y0fnvsFc8NxY+kQ/hv5GQBxZf1Y4fH+73SyN\n/SkQ0AKbigGT+2yjneIKxzdB/W6S9YdRQ8DmxDRedwXa5reVpXRjAK8qLnmN\nlirH1xFbv9VrNRKo1kwrwxN/JbpvnWQEJVD+nGKORn06su6Fyr+iBcPb2XGS\njIFO+R1DVMs3T159juqyRrmMwIyqKHXKCgStCM8P0k1fIfMfaP7aXyH32e1k\nDwRM\r\n=Pnrq\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICWwuGoL1X104VVHAg0aFwafWyHwS7vAoUHjmdBZvIgiAiBMExP35z8dVXQkTvHo6zEQsyEvc6sRn8gnE0Fe20RWAQ=="}]},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.0.0-alpha_1601394416115_0.023879320105751223"},"_hasShrinkwrap":false},"15.0.0":{"name":"restful-react","version":"15.0.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^1.16.2","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"c1bbeaaefea93c0c61bff2f45149d66b74ee82db","_id":"restful-react@15.0.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-HZFg4JJPi8oqB/uCLC+3dclN8e70VSdbvJOBTdSzrCDe9szeEJG4cotvefPoRxMeJ0gHIWSNb54SB+jC/y6JZw==","shasum":"51541b32867ab128f7029019c3f1f04c66486cc2","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.0.0.tgz","fileCount":62,"unpackedSize":602769,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJffcKDCRA9TVsSAnZWagAAHwoP/iEfq9RgAbAO5Hum3rI0\nqZqGlH3mJpaYRGJE5bWH2Lak3q+vOU6GL0j/R34Q4VDFeziq4Mj7MEGLnLVc\nB7XkQBjq6yk4MaHCfqXNHibBURpl2xKAferaZCZWzPNhL+HSEL+Ci7IKIHEn\n8W4hlByfwad/I0bV04bvYVPit1YpWZnXxPOO36gcoWpsKIjc4adGrPDEaxFc\nexjdvTjb8krD7fgzq1Hs6kPRRbK3X4fooVSeTHE08V2iafC2Ndzhdc8cUeiH\nRF0acDH4djo8JEOy8qgvD6/ZybX9pm1X/ene8WEdTPte/fvHZdqw4nupwgb+\nDk5GHttm0/Tca18Zh58wkDHC+KySxzVdK8WjDDMXA4c31BGIzf1WpCT25JEH\nAVL5btzKz8AQy+abl2AvIikVXYSBshRk3MEfqvKgvDN4wYFy7psi72sDE8wJ\nZz3Tknj7c/d4QrFDn7ymV7AMDJF7/Ztn+yINwbx0ofi01eI7AlCdbgkWc4xa\ny7W0WK6q6P53lGW7IKWI+nX+NSTaQLTUqodYpKFg0DKwHaR13hL+mlwoPerE\naZ4W034Z6+xbF5dxN3kL15tCPxBDAukYqh9kW8EShUPNtNxS6htZfWHdUnx0\ndMesACqed41k7Ri1EJZVJW2KE5H89m8wxs0wukEGrQpqdLM0jHoQ2nP59Ery\nXmL9\r\n=sAQK\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIF9nNgo4W1EqQ1vz7hwI97JQchvrZfvEis8YLx68k76xAiEA4gZDUAT3AKsOYQ0XeDvrvE4pmXal53aRJxojww94vhE="}]},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.0.0_1602077314504_0.4353573908041297"},"_hasShrinkwrap":false},"15.0.0-without-cli":{"name":"restful-react","version":"15.0.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [`restful-react`](#restful-react)\n  - [Overview](#overview)\n  - [Getting Started](#getting-started)\n  - [Features](#features)\n    - [Global Configuration](#global-configuration)\n      - [`RestfulProvider` API](#restfulprovider-api)\n    - [Loading and Error States](#loading-and-error-states)\n    - [Lazy Fetching](#lazy-fetching)\n    - [Response Resolution](#response-resolution)\n    - [Debouncing Requests](#debouncing-requests)\n    - [TypeScript Integration](#typescript-integration)\n    - [Query Parameters](#query-parameters)\n    - [Mutations with `useMutate`](#mutations-with-usemutate)\n    - [Polling with `Poll`](#polling-with-poll)\n      - [Long Polling](#long-polling)\n      - [Full `Poll` Component API](#full-poll-component-api)\n    - [Code Generation](#code-generation)\n      - [Usage](#usage)\n      - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n      - [Import from URL](#import-from-url)\n      - [Import from GitHub](#import-from-github)\n      - [Transforming an Original Spec](#transforming-an-original-spec)\n      - [Advanced configuration](#advanced-configuration)\n        - [Config File Format](#config-file-format)\n        - [Config File Example](#config-file-example)\n  - [Contributing](#contributing)\n    - [Code](#code)\n  - [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n### Code Generation\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"c1bbeaaefea93c0c61bff2f45149d66b74ee82db","_id":"restful-react@15.0.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-58sa3zIqyFBTiT7KMqPAQB9EHk3ZuPTVUBn122MKQ+M/uoL1V5FLHqP0L0vAfHa8lIyD9uqcgg565Re/TGNtQg==","shasum":"33b899264609d8d440544d2cad58fb1f381ad377","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.0.0-without-cli.tgz","fileCount":49,"unpackedSize":547902,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJffcKICRA9TVsSAnZWagAAe8gP/3mjEGwBYkz7rzS6dlPJ\n+tzi4NAdSG/OK78U71vOQ4gLurQ0x233u3S/q4oeDzZYsyCRryIj5jTWKCKK\n/aOzmXHFKcurJLi3xblZvZ5BZdR6kVLqxzsc7isqmMPtQ/lRTHN1noMb/ybg\nyfBOiN5roSglJPN0DAYyNul19/gCTjW9rgnNgxDRyd1hk526Aj+3r+ua5LyW\noePUVVQgRbyEYvaLyNZLy7CzK0cwplk89BKDdnslxuRMORy5e7ehraqCFv+W\nYsu93FuAZJhE3mHp5IwNxFvMHGjR2gBWSOzAa69UHr/s9pzfbZLH2QNJGaz1\nSASFXsoRzdB59SLpSsLHUH1M7Cs0An6VxcCVh5YZZAXy7EJRr21pJ2glNzRz\nYehXxeB0FceJ54AHr496wlSN9xydf2fNjI6671d2aws04bmJB9lCqRvPPNcr\nbb7GxrTs2YU62Lj9+Y4X+5WNKWp333MlJRYJF5/9rSrRVXSbo763wF0Lpuq/\n7miJFsU1YvE5rxq1HGvAMiKBHRjMOViAVk9t6Hwq9/ICmq0Qq2i2X2+m949t\nt2ha2u2NDBzlNi20iCVNGuChXvkfrR7iaxIKAN2W1a05Hlyk7+bKkf72vtLF\nELGm/DLUQWvQ4ZkRdzKAm8vyF8r+gWJogdrGqvHvbO0tMAIEIIX+aZcdRsbH\nkXOn\r\n=N4Ho\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDslIl1UvAlsFDqDeOgzFevo9hW3W/IBUtKkjrnvIPaVwIhAKpAz2pn7vut1lPYIT/FoZvNHzMG3lVFXm9dhiBKCntO"}]},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.0.0-without-cli_1602077320301_0.972028204269451"},"_hasShrinkwrap":false},"15.1.0":{"name":"restful-react","version":"15.1.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"30abf577750f63fd7a916ee24b662f43e98a4c36","_id":"restful-react@15.1.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-pVzIp86v6N3TTsI4Og7PeEX+4KEVv9gzIoJ4AZnylpCzJRhTn+WVSgcm7j6xEJg6nY9BT461U0XqFHgU8sk6pQ==","shasum":"f4253f2908c9e437372c4268f7f99ce9341116ac","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.1.0.tgz","fileCount":62,"unpackedSize":614832,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfhAbzCRA9TVsSAnZWagAAWwUP/3w0LEG6F5NLK6qKbvq7\nyaH534lwagz7eqOouJX1uAMEQ+n7NdoCF4fq+kdjlPuVRpJaZk7CrcDLwQMI\nQbxyc2ecumyOaBdnEXrrdqHk18wTFotsB5xIAQkprJMuy2baqoaTg4Ag1tDc\nTrk/qEdsOSVO7CAHkBXem+ht/OU8M5MIep4d5uXcxIINngS43JoacsCDq3EA\nhk0TF3ZLcPOi1ombEymxUOccBLsOAt0YJeUW2R8FdiMOp8Scqqq67GdgJDMx\nxTqfZMDt0seOY2Dm9stTSNDm8j/j27X374zV/c3F9JwSmXgHzL+uH/kKQUYe\nzfcdIthn5X1vifaxT/mRqbF5zDdMBNa+/AHPpO4OacywoCVqUiKGg+ygZqhN\niw3rsEI6Wy+pZ1G2rCRIX8h289AOQc714OjrgcWx+1nIkAvl87UqItVufqsc\nj2IW3WMnYM/imeNikoNgTJ6n0z6NNn8feC9LJvdOjz3OQE6lxNeXPwaGatXa\nMA6l7AJfzp7AwwOBdlf+fvImVL7eQrPdHoPV0J0h7hcoUBoM3jY3qJMGa/St\nQWyfV5KrKDp+e227OePeJU+08bhJednqsHfpCz+IB/UaDKAXythmv+s/nvLY\nk5TZea8uorwyTpxtTnJhI9JBBDu7g4kaCrcjW3MLSe0n8rE2BtWdfSPkpd8L\n6VE9\r\n=udQf\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICB/vnLxVNzAIf5Xh0iUZyFkXvY+AOXHt6pU685HcrKUAiBAlxBITC9TOPM4M5Cnpi/RY/lGcML+5VGbbFn1Ykwy0w=="}]},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.1.0_1602488050895_0.3740342003796304"},"_hasShrinkwrap":false},"15.1.0-without-cli":{"name":"restful-react","version":"15.1.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"30abf577750f63fd7a916ee24b662f43e98a4c36","_id":"restful-react@15.1.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-T3YqYHvBfNWXnP3ls0lxPKV2XIDeDaj3d/eH5sG6KhiVj2hR2zUmFK97r+CYTNsU60V9tlYGKBLs40SsnfOnvw==","shasum":"666b3fd4f28ba1f4396deefc7df5ae81d99065fc","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.1.0-without-cli.tgz","fileCount":49,"unpackedSize":559966,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfhAb4CRA9TVsSAnZWagAABpEQAKHQ+oCWZWDwobogqrmU\nDIYDuYYqgTEzEmZLZ3xCq72rcyM3o7/n/D7Ws0GVprBpn0qB41HRw2H3IOme\nPbTQAXogNFoe9OEDC5i54MDU0dudIZls/YMDV3sxuYWKlc3Jc+33tQ5HDnKR\nI9WlQNsP+K0Aw1M1HkJxWUpCzHmGtPiLRReYHM8T2jOKT1TRnKt2HaI3l4uF\nL+/HLhTnmWXT+297pvKSO0n96fHcYYzg3isSv0pUCKZ3rWr67uvfxkNf8t0i\n5yJjKnlTATQaDg2UO4INatPTLU4uNQm+VhHPnf7mZHcP3yJynGQy6wf1XyOK\nJ/Ne67mFECPil2Dm6uAXN1AfmCHySZ9J+gO9euwT1RvLqCOBOwHiiLxwwkQw\n4RjzAgOttQscm2fnHSwhiyOSHQYCX33QX/wvXglYE+wbNbQWpmgLqWS65X/N\n5ZA/fBIUCOj0F6CA5aP532atTbEVUYhLlF3/FOfE4DmeDlnyRwYAe7iLzHZX\nOaR9CsOfolMFHJkGF10mf1WRg7OQbL33e7332pePFuxr315zQdMKVgmgu1Al\nz5T+6aHXZpCupGanN0yPO3zuujhQk0jUnqSuexl2cqd2ZCd2JzfGIefZg+yD\nAdTfM+aAr6kWrLDWfa91erM5AqdgBDin7zaDLuhdnw1+w3ykMJZovdwyameo\nt4Np\r\n=FvD+\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDk4c+pBGtdcN7PLdRFRaACERfv190fjDiGRp+i/cwB0AIhALNAY5Xe8Sd6DUHsEeMF8tvRuJxcwVf0dumkTM43IKH6"}]},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.1.0-without-cli_1602488056088_0.942766486760596"},"_hasShrinkwrap":false},"15.1.1":{"name":"restful-react","version":"15.1.1","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"96561e7c9f046ed4bc4fe7176c4408a89d297d5d","_id":"restful-react@15.1.1","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-LqqrsceBhIoZj/K/wfjsT2NVXrEFjugR+U+brvLXMKJxHPfA0Ai7zTp8sZj8Yk84JYiEFat7z2jPixbREimuCQ==","shasum":"dc4ba949899cbcad6aaa848e1227e2ffbc58448a","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.1.1.tgz","fileCount":62,"unpackedSize":615025,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfhv60CRA9TVsSAnZWagAA4zkP/jLAWM2XT5M3LRJttehQ\nwjXS+l89u26CxcZNzaDr/OfkPjqCpv8XHQNoAjZH0LIVY8FYbDBh/UywQUC+\nfUA14+MsMwKL5pMt3lUP63THWCBjzDgS2ENzPLpmR0xSb2LROmCaERg3F96X\nSEV5B57IgMw+oxokG+gJf9h4VOLHzXsEsBbvUHWz6UoQIWPkCjokr771GO+s\neLPahCzKiBzzhADBwr8isfzHnj3+BST15VseVbLZhP58Kf6wEe++5Rfbbmyo\nGKFxFpWlBmWjlTxD8x1sqp4EkOut+Vn8ZwtYfzeH7us01eQtPRtuacGkOEMt\nzh5vZ6gMX7m1R2axoMF379BIQcEEdqsyaThoYc9FiHXvOpWry6h/qB0xe5s2\nrCVgu+R8nYpuvyXlTQWzppY5C5Agh4zwYB3jje99ZukV3dk3nJ/LGzZZGiqO\nFLFvb/AG59J2QyHMNAsVRe6ERXNyfSwe0czV8Z64QZtMipCXkDogToteD3QU\nm8xkdOnxHa6BdH1+nC2LjAGq5hFTWtxKoGeJL4I69vSAF2lRAgAG1kl+hFsH\nQSjSyBJNb76l5m10fvb0QSzzh1P33i36fCo1wO0TE4c05TbkI8wLptL4u+3Q\nWJRmirTU2CON9XROeNbIgRQo49i7vedU04DpElJnQX0cleLbFknXqa+Xkm5G\nAb3H\r\n=YX2Q\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCRS9VfqQD1v4wm8OzLfXXXE0qpjVitbpNfsUqjCfL+TQIgaNUFLdy+QLZzlTEKk/E3qqJob7+0tKz1LiKtEn6AtxM="}]},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.1.1_1602682547551_0.7491914541319442"},"_hasShrinkwrap":false},"15.1.1-without-cli":{"name":"restful-react","version":"15.1.1-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"96561e7c9f046ed4bc4fe7176c4408a89d297d5d","_id":"restful-react@15.1.1-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-A1iZOc4hTDC5yOecrBnmFQSfiX31Qehd43wYLG/trxg0OrRqRuP35UA1bckFEUVlEdY1wFRDF0L0oDkSSA4MCw==","shasum":"7ffefbf416b6de5112404a8407ff1cb2f8f036ce","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.1.1-without-cli.tgz","fileCount":49,"unpackedSize":560166,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfhv66CRA9TVsSAnZWagAAlFAP/jN2rwNZhq65v3t0E7ZS\nEPxZqtvag7C9Ywza5YR37xmKntr77D1U+Xm3WdqAoopdmKPh9zAeeBvQMG1a\nYrl/9vrT+7Wuo/DE3qonTsUj/3ms2CKO3SbIukOcJoW4m2rJa93LZ7QtWGwr\nhxxCaohnFR3FMlJWLwW6eGK95X2fULD0uwxRA7tCg5IuH1xw7OPXGsoyNvi/\n9uEl7v7JGHl2eLoIkWIxnj4lFD4UqPq5h7rpaSuqLE4mIGCRlOkBUpo/NoHb\nYyzy1dQC5Ffbuw1sdk25WpHfGAenBSUjMFTRONWCU9bsQiyXlmXsDuiU1X1B\n73dRYdnFTzNB3SB/3zBRhhqX5IWRsiNtcHzvt1AtKtpHuH+NLb94Lx7f3OEK\nvyfH54IohCRaf5uC6ybFolZLIYE3ysYeX/Lvn8m0o/4nTrpso1fnibsyIsIK\nW/yElPiqiI1kSyZDZ2EKh1DuS0HVhhnWA327EqAjzZF3LE2ZW5I9ABcmCzw5\nZdhCaEIfToybAekoPsxm69llygfox7uG0SPgpAybR3W2jxlPSrvbXWxoD3fa\nJlkMB9zDDmyvEDo3uA7raN6S1Q7rA5FLXu7dxy5w6SxvUvX4rUdJwVWf9WF9\n+6pG1Q03nYez1pDOIGdTBlFOnsWWIDFUGtgyJTUsP+TMF/ltBOzE6UB2LmIu\ngx7c\r\n=ZQQk\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQD8vj/v2Qs+R1s1epWxFew9asrjMUEAQUcUTwRaaqKC1gIhAIk0M/+RBtBJFeesQIIZmXV1pRJhRDFbEOyN2jVfjHQd"}]},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.1.1-without-cli_1602682554376_0.1340993748913608"},"_hasShrinkwrap":false},"15.1.2":{"name":"restful-react","version":"15.1.2","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"554a9c7642adad7911f705ac03f2967c0d4906e0","_id":"restful-react@15.1.2","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-80ZVBLonrckTKWRg8bET7tCRyRg5WeWBdom937yC9xenKb17DGgeEvY90IOeDjJkB1k0fARA9l22i7yfWAA4UQ==","shasum":"2778e0daa5294ca6a0a81e4cf51558660c7c9c92","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.1.2.tgz","fileCount":62,"unpackedSize":615475,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfpUSZCRA9TVsSAnZWagAABRQP/0JMgQu5xMV4SEV/cwR8\n9jj4HPA60PpOKjyUqe63zJYvSQ8koE/JFQ+eBoa1ue1hrv2GuMOVKLdON6bW\nAEN0iCQ+/2m7Og3V/5HJl4lLBjMYRrrGc2oUFPZRpwXRy7wrbwuLcW/ErqYF\nQwqBtJzg524KVu7W7n8CRDgDQb2BpSfnFEuD4t0Kx+S5GZ7yi77U3blEq42d\nv2/5p6xQ/wLuugX6ci2kx0dehcB9r9TbHnmTaOfjLN0HFwxNc3b9m879eI+g\nJtIeLmXfnY+ZOkm63jtLtaZ5uoyJnFgCrQCo31lsPLy1iATovm9USHD6UiVQ\nf/na7LEhCEGjefqAPnyGd9UwcUih1po72oMi07+zexKqmfwdBdC4hX5Tu1Ut\nnMIP4xaxS85JdfxjQry8p5yROg5ME58ZWyW2kME7dKSfGAwUvPkEhE9VzX6o\n/W9A6Fye5zJ3OuQ9wuMqjgXWJMiXc8NIKqt1JN+12JTyaNlwRtLn6mOzwX/o\n4ml00cHfUfgyr+hmgd96GczCtP3jQSPJphLyLwtBbdPFsQ1e7REG+QH3eTiN\nwk8E5BLDdvoCsPPrxXWkLkHDhyYArKw7BSsbvnMLgTWAPTFFr7O4GW1tNgC6\njsIAIjDAcHVV1qovZs6FKoMZjl2u3su32D/2SacBosrIe9BOHRtrv0mDASMC\nSxYT\r\n=9nYS\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIHYf2miFpPUKU3HciZIHG8JfTUuZYfepIlPj2bk8OxCkAiAL6cDb1ggtPAGvL4AaUAuutB5G4G8fPfeLWwKyydVR6g=="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.1.2_1604666520895_0.020424113254559284"},"_hasShrinkwrap":false},"15.1.2-without-cli":{"name":"restful-react","version":"15.1.2-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"554a9c7642adad7911f705ac03f2967c0d4906e0","_id":"restful-react@15.1.2-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-cUaaJz3z6tlaiXMyhl1xAVBrykRWBLTeaeYz9Ddoc8HqwTYvo86JO8euRz1p62LX8nJC55lpgJ2188vjmSxA7w==","shasum":"dd737f183894bc11757b6dac153bbabba94017b2","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.1.2-without-cli.tgz","fileCount":49,"unpackedSize":560503,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfpUSlCRA9TVsSAnZWagAAEOAP/jc389mVT3S+sr32Ot2j\nlCngLcecDGD3lLOOGlKBDLJVlTcHPo30AL0cENAEcCmIRB3PHKgpOeXfiRsS\ng7SKumoSpK0QM+0TKMBIyXOWytKJGMq256l9pEd2NluTF3tykvDlcOqT+6cZ\n7Ig+KX13/wc2MHd6VyRfWfK53pbbS1++HFDAj5juW8TJzq/v/31maJAILtrM\nKCaHS7ZE8BtISmuQchJuzflITV39nRK14s3aGREf6pP1RpokEhHU/267Qeeo\nz4lMguOK4Df1Nmc1ltDiStOh/YYBKFKaNtn07EIYPxiKEtr4aqNE7b9mxBdy\n9mTrZ7mIZmOGeWcmkB7FHzvEsVOEWCa7fE6/UokYt4N7BmLWmdoDu9FYsPZD\nsMtkm9fXXBRr2KlI4qrVDhD+icxVVjkQ4zeQOHxffMAAuaK9BuXI7kUQ/WUI\ncClj6MmNt/zrs2g3sQwtzLQeRv+nRRnLuLIxCbJLUrQe4k381e9iy63h053V\nXzynincbR7OS2F0vyuLJ0ELAgJvG7q52lKMXGjOEZ2dAsySTHVnO0ID32F/g\nydZR6Yx8MvuZ0ThyWT7osD6dSQOUGKduXDnojuFKQ04Udcf83suvDLPkvCAe\nKX246wKEzBevXB2g7HZ2lLG6HUZ+Ab65oo9zxHbE0q2C8J1ZRvEYJE9rEKDA\nPTQl\r\n=SPpF\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDubBJdWOgYtc4/4Admm50DktJIyT4MupRVcQKnVmII/gIhAKIvjp5jnA4DuDyB7uyz6xVftQlzem+wL+AiBPH66fE0"}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.1.2-without-cli_1604666532355_0.2973930189684437"},"_hasShrinkwrap":false},"15.1.3":{"name":"restful-react","version":"15.1.3","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"dd5e4a5ebb64e6b04b5f2e41b1b9e41c9a56cc35","_id":"restful-react@15.1.3","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-QDph+7WmXiEdmEfQtojkLgQD1RdSoiZXEhNIxzVB01Wqjh2vJRtN70ztWnIBE2mEVsIeK5UAaUQjWWy3EKVoHA==","shasum":"475af0781e3ca89d78b3a5722f52ba31d097e9bc","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.1.3.tgz","fileCount":62,"unpackedSize":616307,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJf00ykCRA9TVsSAnZWagAAkZsQAKUeFK7idrfmAkQJixnw\n76C0HiXm0MCE6rDIqW8iysM4Jjf9AMBQwBm1mQbqdNO1kRduT1UULVRGj/PH\ndTUOxM3XvO+dtCYkBBzjlfBqFXvRjL+CfqC0O5nTxB5tKMC1KE4DxctM1PA5\nnzsbScZx8mAIYyGawfkKpEfF7nEbXw63TgH49okeByrF0qJNPTe5RP+M4bRU\ncmY9veJsWJ3XWJE3yDoZsNeHOmbnnq/OulQdXIDWeEzt9pnmHbSvS1h0hTdk\namu7uz+/IcGQa8upjjBkZvuPxS6IFkkUDuL395egZZaAkCX0SVEziHd9B4pI\nbGbof+M4jQGM7GQzADnfHuOcABSANnN90RDzf8SqswE1+ltVh9y0w5KIbKSI\nmLNkWsyYS5sEXEda3SWDxQF+74FLunn+x1G6QyWbxbp/Z71m8qudUZzg/Y0O\nKPND4IG2Se9JBMukezTaO8Sg+Cl75vyQZm61JR193R90qS192k9q8qsxbBVg\nL+inizesqWektuxLAMGXBBQjCDUf69rKvhpnPj+XcUXJ4g0tliM5SlMnqTVN\nQfR+iSGGTx/o+G0mS7ohIqPMFoptCWMOpACpW/cTEHN+wY3qHnG6nNYuELpP\nsfFQxjYqO2HTNNJfPhV5KPgaWYyJZU26oJWW8nsFRv6nkSJLPF4SakFy7TYR\nZDNX\r\n=6jw6\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCaV7z1DpZRX/B/tlhrLA0fhCg5wsMsgR/lEzkq553RUgIgSZCHEkUPDHnDqWCBosNR32qIP5nDZYxxnc2uCvPY1eA="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.1.3_1607683235583_0.23806591043064862"},"_hasShrinkwrap":false},"15.1.3-without-cli":{"name":"restful-react","version":"15.1.3-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"dd5e4a5ebb64e6b04b5f2e41b1b9e41c9a56cc35","_id":"restful-react@15.1.3-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-9OnSpX1CZbaATO6yYwMYG574XCQWPsNLBB8Sd0l2gAb66Iz+jJX/5i+V1+hpN6ziIy7+01Y0Q0sPj9LprQgs8A==","shasum":"429843b4c73f603a2b99b1175d7eb3f15308aa71","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.1.3-without-cli.tgz","fileCount":49,"unpackedSize":561335,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJf00ytCRA9TVsSAnZWagAAEZsP/AkSnUC42Dn4wXv4xr9c\nuX1QlIYR18L8BuQSACG/LxcVQ09oeuVkYMZ9ctG8SqaCHuLOU4ptYodm4CgK\nFq7HAAMYDN28r+DfuJx2rka6NO0NNZOM89vuD9yMj10xf5qqZZDWHVy0UKT/\n01X0ouy7DP9gAQcp8bRuvTg8hln4btkqortP4tDSpJXcqa0tOrfwGzq6i/GU\n0rm+2VIsWILl1tCQvCUexJfUBFgG3rnSPhbcgwHFjMUu5Q7IlEr+zcA76Sd4\n/hK77J338rxVI1ciZ3rjPD/5NapYA+UCvhTi0fNVH7EEX1cvw3d7y86wJfm1\n2zW+G8svFhETiXqzYEwJmW9qeH3AQaoXzlY/wXLw6PU4TPsVMBc90IQzk1dH\n7b+26rV+aA8AiII6KZ8PYxcvs/JPGc7KjVRu9aUFq5WAGi/gNiOwE//CPtt1\n1U3iurQSI0Zzvd2CGokrJNcRCanudqhNfs5oPBfMyRWiMGbU9Aik5vvX0hdb\nKJ3r7PUOj3oK8tDdYkTTLbVLBeYL+PqPiPG5iGEtezDnO8/jrB9x7GI8i2Yk\nN3UlldM85W5HauMdjB7PStsgk+WqLMVcXJyX0FiEPfyye1G8Dd6e4pbin7/x\nsqkEv5lKpnQyaP+UgsDBjto+petfOeauhGQ/M592mkR7NKXx9njQStlBcfVF\nOTEa\r\n=/0ll\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICy1SWzajXQ6bW55zSsxZEXhoTbAWjuOFLS4B7ltM7NKAiEA4rZqmVVODjsI96y6V8KsHhraRH9uUng07GOyzJTpais="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.1.3-without-cli_1607683245281_0.28791656807265875"},"_hasShrinkwrap":false},"15.1.4-without-cli":{"name":"restful-react","version":"15.1.4-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"3d28a49e2cb0e898e030a7f2421b12b27685ff5d","_id":"restful-react@15.1.4-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-iWqMcMG6boRd9DG3BjJYuB/rbUAlNtku3S3YrWOrg2DC0c7YK0k4YS7tSh7i5W8L+J1uHOvvgikTkCEHjEDt4Q==","shasum":"9d97fd71e0d4eed875a5f9bc5ef9ca1b3a4e0c62","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.1.4-without-cli.tgz","fileCount":49,"unpackedSize":561677,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJf8t+UCRA9TVsSAnZWagAAmfQP/2t693a1ekaIW4b68Gce\nQnrmYDzKxu6K2qrzcqSow1g2jYclOIgyrpv6u03Ggq44xm8wx0BLlE9Gnxp9\n7UUcn0N0EQqoGiElrbARfazECMjgXIrIq6QSDpRszAheKzt/ia0wIIW8sUwy\negBJF+rvCTNO7Tf/qzlKxP/5vpzwDnPt7VuosttyHCR4HuVaRVo61DH8pGKx\nW39fXX3kLcLGkUxw//91QS9fPfPZEghJBRdGtOva+0DAHJ4N3CxhkkbB4/UD\nAcd96s5Qiq7k5xFXiAUYdfuIkSxkZmTl4vxa/x2moZkRdNxn1RvZWW1E5ylN\ncuW/FjuFAank++1oPIMn4gyOacavE580PezUpPjedlD4xwYMS0Isj9v3QQfZ\nCMIktI7tHo6nCAwJG+t6jPXKh6+JbRDNFFyrxvWQ4lPJ948+ba29i4RWa1r5\nEFdvIFdStyDUZZZi4zMMAbdRALvVAJ78VROxtkMLCy8ScrbZ+x8xlpWGqpEP\nyS69mlHt/T3jQW2Qfb4IEBq9DXE2cciGWRwWG2jHeTeIDl7rdbTfWJpmdRwR\nEQFuxBIDwG2GPL7GZLrKRFG6ZYM+mFWYasKy26KQSrhG0BrQcwAItIdTeCX9\nsH2BdcjMLVAyIr0+r/DtFZ7eFw8pd6CgX9poZfiL8A+VbtTnuDAf7XQrMk1g\nktlW\r\n=Azjz\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIG9emDw+qpdvr3qXP55qYVcpumSofDNnpZPkfmNal8NaAiBLO3hj2VoLWgQLvT8i6P3Y9OkUHmteICXKyPasiNJ36A=="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.1.4-without-cli_1609752467805_0.13079933165076163"},"_hasShrinkwrap":false},"15.2.0":{"name":"restful-react","version":"15.2.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"2793720a82940ed28ab6d34380e98f46591b56c8","_id":"restful-react@15.2.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-U0ccpZ7ereB3yfUZj2nYqMC+0yzowYl5+j6y7HSecexjgnunbnZEYY6UFSXUBLOPIIr56tLcD+/AEcb/eIOD6A==","shasum":"54ac2cd2fcc827210be3fe043b8d9b5a0c9aeaa9","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.2.0.tgz","fileCount":62,"unpackedSize":617512,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgGDAiCRA9TVsSAnZWagAAye4QAJLWSUGq5U/pFv/+sYlp\nGg3rdhGL1N4Bai/1nkADNGV4FQ4nAoZrCoChXTRnm+cs4pCVu2u/aOrpTHU/\nzIRZplj0jqgVazH+hdOQoy28W8vXOmxNglE+Nq0lBTmAU2/dyhkebp06qR9W\n83oJ53ulsoquK+i4cRKN2T3aV4H1FgKLTbb0UUZbL69eoTTl+HeohIHLTec+\n7Neht0JYRZlMP/xBJTG68zQXUWCj1nC4hesMuALRMv+hh1bJLmKwL/NPJI4e\n5onORCAmr4wzU8lwOdWnpUjL5Y0zjJFylXKHsXXT+OMDuxUAm+lCgbAAaaaD\nksEiHdvCA26Xr9xANJZn1Y9SgzWn9S+7oWh+kbqld88+xxttUAYzIi/pRboU\nMqusd1SGfzrlINTfFjjeMIoKPAiTBXzE8bhMaK8eMmtwmw4B04Lf+8frq4vA\nNKePbOlutP0gV14gfvLha//jTs2gUaUNFDDBCSHTZW7MdGv7lMEPvSRZ+plb\nJkFpxBg3ZE8XWm81oy8KnsLmoD14eyVt+jSMfPn7F5I4JB23D24GmSmQOCOw\nQUVN3yRaJBmtejyu6WuTVZjTYc7c2wXj/6dtpyD41n/eY0iwRXqunq+ilvhf\nIrkZSTu0wO86SemunZr49HRkG0gC9HwdNw+/rsFk2GEN/5c5WcCaFH2JSuuW\n39z/\r\n=xup/\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIEIpyAu97ixBoqKsVRpDNmMb9nrVeG6m/PmEg8qH5JfSAiAUegr+JzfEEHmkr+I5KMaK77ATELox/Rvpug/weTgCbA=="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.2.0_1612197921889_0.09137102353908566"},"_hasShrinkwrap":false},"15.2.0-without-cli":{"name":"restful-react","version":"15.2.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [API Versioning](#api-versioning)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### API Versioning\n\nThe generated file will include an exported constant `SPEC_VERSION` that will contain to the OpenAPI `info.version` property's value.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"2793720a82940ed28ab6d34380e98f46591b56c8","_id":"restful-react@15.2.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-GYByzbgjVXza8iHX+C2mD8b6pydgfy5Ch9aocRgN1bXCReH7Uyt9sxIBi+UwzixhSaDFxnImPQDtpQcHrwf6XA==","shasum":"101c0901de5300c717c8d54fe5ca7c085264db85","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.2.0-without-cli.tgz","fileCount":49,"unpackedSize":562122,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgGDAnCRA9TVsSAnZWagAAqfgQAJOvnXFDsHOoez9t9ama\nrATn3x0aEXm/o9eNN3pAcTz+XaxUkBAoKuKDYjzLg1eIInFk6cN9bQAIGYK+\nCTgeJVz/wRVXi1DYU5ybJzA0QSfBuJRQCwZVWsN2/pumb0omCZd3aD0qBFAE\nf0tULPiW1pxiH4Uk9Kl2ZKFv9W3B5qrcRCCi8CJy/A0sfd0DDoipvRYDoK4z\nGKMuQCRuU+72nppmWUJDebvIlsSOBioZkRjv82ZnGDMfohbKyv/MvFDxCE1q\neKGQ5Pm6no0Hwqps0yfoUG8mokgV5ads+3BhWHbvWQYQtecbv7oNGqfm9N1f\nDGDE7y70u/uOU8xPSt0JtiDUGT1cDcHPEfyJkF5Zp7GAOWJLeN6d6rG8pK6z\nd3j2tz9ND61qpXLAdo/ent7ZcgGzYF5OGEztYEr+4dELPmBzTbIZVCxouFaq\nGqhRXGvyc20lBlPZFKzdk/9mEmWofRHot58jnmq8DCgrWDdr3XT9liTrel8N\n6XPtxyOyFIqlkedwAP4B0drCtvUopuPUUKn/tLQYJATUxWRZUPY/IrmCdwAz\ne83MIg5Q2kaSqrPVsAKyWMMJlNErNSROeEAyAsfl/kIkFDFQRhe5otV6gJuG\nlAuuGDHI8K8rtK2aT+CUf7K7FtpUUPVBSaJpd14pK+uEP3iQD+7kFyK37f+z\ndh9t\r\n=53zP\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCGrgRoSNGt41MZ2ogfVt3UUyLwWq7zej0A897XKf7yJQIgC6+zlsiAnpd93k3pQqSodNPIAlio2Qdt6Df4FpUUa1c="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.2.0-without-cli_1612197926579_0.2562079900503773"},"_hasShrinkwrap":false},"15.3.0":{"name":"restful-react","version":"15.3.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^1.10.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"b184ed1201b62171b3964f6bd9b31edbaf7e159f","_id":"restful-react@15.3.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-FrvvwUIxu104kWDAXW+eGA4O1+BVkXYaNQunLyuOdMzhwpP4TipOfNkFDA250qnqhv8hBAQ1UgZAJLumC2sl7g==","shasum":"1faf02a356ff8c3d321e412b34901bdd145039e6","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.3.0.tgz","fileCount":62,"unpackedSize":619669,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgWMWeCRA9TVsSAnZWagAAsREP/1r5RY/tHpJaN/CSPXzJ\nuIfgHGGxHEeVOeIQUeVKiG9iAZM3cRmhWIsLr5BXpd3MaZj901sjfSXi5wOD\nWtSdG4C0C87VtScjH61fMtbZIwnmyjh6oCxztBIkVjDvSmuByoO9MPVaJZQl\nVKKR9H23KGC63DeZVl60KBB7eIueevu7auEKJS9M43qkBMN/at5JjW1itYVn\nlPsEe5VqkS4eO+tXyZJVQ7A0M4SB4kZyNWiHffCh91RUcUOkVxVzXwX5koy9\n6vCGEpBYZheOAbvbWW6jT6DPH172gqAaBO9EAECS7+crwzcX/KRJ+b+1Yjbq\nzorg4cR2s2VHFMbk8OBxGcwakc5U6xst1cV2ILsnR6s7QtyVXYa1kOLsApKK\n0ubIpktoejZ8rDTy4z9WemGMr9uDGhDquuqrRp1SY9ru98ZPyZpUPpV9aNk3\nk/8WcI8BLGJt3xozdTRy07l3+7PcQWmqTEl1AvFIQFHgUO4F6LCJs2OgIIfB\nk1VK+bxa4l10CiuMyFZJsAbEf3Kxbu3ZvVLSPzYungRfKkRZ4U+xZiBC/0Iq\ncEW3dyJ+8qiLZQjvO420tnq79Yvrse0HfFL8aJ5hpLBWvuYJieMF7dtgT+7Y\n0aZa166PcTmGagWC0T4T2Bhzlxosxg6N0aPc35+dTgp0WlnBlX7BPCu1E3AY\nemm0\r\n=7Ueu\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIFfESAHmJv+PetgJR5MHwH4qNO0SwxJeoD0D8CfwX9m9AiBuUQreFEKS0bwS7eEtPKhQimT3KP+VaXf5G6DgG/lZhQ=="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.3.0_1616430494119_0.1788956689639385"},"_hasShrinkwrap":false},"15.3.0-without-cli":{"name":"restful-react","version":"15.3.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [API Versioning](#api-versioning)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### API Versioning\n\nThe generated file will include an exported constant `SPEC_VERSION` that will contain to the OpenAPI `info.version` property's value.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"b184ed1201b62171b3964f6bd9b31edbaf7e159f","_id":"restful-react@15.3.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-K6tSA0wBiLf6unjU+qUQXzxSUi6Npvi5ElpdfHFyP87LmIhZVbitTbtUI3xOeVorYVYfMAaIN0a3rF6Y6tGe5Q==","shasum":"44d5eb50f98221445d2f0447b5ab080b01eae209","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.3.0-without-cli.tgz","fileCount":49,"unpackedSize":564279,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgWMWkCRA9TVsSAnZWagAAfY4QAI+XcMHjJCaJXD7ZQgkx\nXTaHhCkDTnfL8k9hdbHAAILOWIG5oIwtVOb99mCWeDRfZ0JLO0jdJ+bgTBei\nRaxLW8RKGobSLpPLgAfyhBjepbJ2odH65qBF9THG2xTxoh5f/0/2nlB5sPb4\nZrN2T1FrFIuYuySqYvjU2UVJdr8XleXsOizrUHj2NNEsxe8Ziw8cn8r9siEH\nQ3AwqwIZkbAwfyuKkXqnfdRNIaLiGBxdpi7HVGuDs43caX6H5t1kFV3Gsu99\nFSmYCVlbKNQDteb0Wo41Z3pg+b7r2jFZvgrVgGknw1A0mjMbCJBr4MWGV9Y5\nG7vOJ97ppmQUZpmNKoZkkZo3WBae1hKHOoZR6Kxik9RXseZ2h9ARHdrXu8cB\ndI3LApncU6iNN4npMFkIGeDYKsSP9VymR3t2pA5xFBSfHtQ6UZkCKHfH7u+O\nr3JV/au2P10g0p3SmKsse1zJgp7Dw8/HWGq9dFqrZ5MKM0TumYYSR27RxPFu\nHZSQoxM0hrS92xu8H2RfTi0asQduPUPCkF+bkx/WJKEQ9q2rHTbR5fUbl08f\nDb347YcMlny0DwuEO8CRy40wCEPsonhw1nfOXZ57l8koLv8U0ckVMqWFOirk\nxNdIh0wNMhiBL5a7lmT/s+uUteM5i2LraIB+HNa6sf+t0Djx6ATvCViHITm1\nxfi2\r\n=jt8W\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCtPxFxnlcaEDL82MtE9ZjIPolC2GcTi8bEFaH5qsiYVwIhAKBev/i/qlrunC6j95pqnwKt6Ru8n1Y2+1Rn5wUZ9dPJ"}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.3.0-without-cli_1616430499794_0.7536797686896848"},"_hasShrinkwrap":false},"15.4.0":{"name":"restful-react","version":"15.4.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^2.1.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"81e4a5140c2b12e8eddc85c837879bfa40bb9d54","_id":"restful-react@15.4.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-ibi+Lunw3KoWVsE+eSQ9De9NPmk/hLCYmHn8az0QIBm00z+WG16KhHwlTard1BjJRkXdPY64gg1HzCHToy9zFg==","shasum":"bc87fe62379467baddad5be5c803e2a70dd282ef","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.4.0.tgz","fileCount":62,"unpackedSize":622229,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgZHTtCRA9TVsSAnZWagAARk0P/29QvI9533MdBd+iONJS\nBRiWQJZFe84UAx4+J/lp5yRhG/QkQ0EER8NDoTjhjJefLA/E9yzyIAcq8UxS\n11x3WW8VFKxy2zJOhuJW2uitvVcFcTRa0cQv1Lwh6cYJabwK/bHZ8u05EBUs\nqYWbwOfHV/F48wQlww1BxwvZg2kbBYmQIEb/CLcfZvKGVEsav2KPNQRsys0k\nGUkydekzqunn2OY0BWteGA2nkInBRHEtRQzTrDvvdCEt2ReyFcXuLvf9CWCt\nJkpmYnBRdwK0tZPoHye62z7m0UR+K4iPpShwDr80dwV4Vhl/e+JrO74qyQ43\nULIeJ9q472AuzOMhpefmDuYMJdHreQpy8HfX7ov/y/gCEez/C4QY2dwolhFb\nmjelUJN0Mm79r6aiyLwkE5t60aJ+O3YkOhVmG9Q9fvCUXfbUZX2OUy1m5LxV\nJm2euOiSd3pNVDONW6L68qGaGiUxp3VC15hFyjQSn5WvQvMEs7/QhVE+C8DN\nVY7x+Mts9VSzobI4QL8Eouf5/tHHq3vVLavCqDkaRc6D0viEj/k6XR003TRi\nXqEimWIJYBXrbIjm32xODtSt4MWwQUYWhwOU2xOoU6tGZMatErF7lSywlJr4\n+r7XezZ11JATm+3NONhCABPatfE82OLaNXlE+h5Jkl09W9wQ8E4V9vXY16N8\nMNh+\r\n=Ousi\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDdPBFlDnFkDk9b+I9K4t2zJFynz1p2HO7Pno/CXso0HQIhANhWI3nsgwOl+K5ckqAiMbii+eQ/wUk7v8r3yHt8IyQk"}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.4.0_1617196269165_0.944004815491801"},"_hasShrinkwrap":false},"15.4.1-g1d6980d":{"name":"restful-react","version":"15.4.1-g1d6980d","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^2.1.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [API Versioning](#api-versioning)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### API Versioning\n\nThe generated file will include an exported constant `SPEC_VERSION` that will contain to the OpenAPI `info.version` property's value.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"1d6980de95c03037b50469e4216bb5ff61eda9ba","_id":"restful-react@15.4.1-g1d6980d","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-87JZ0/Ag4AN/3xQFCDM/bnbNbmQoKdPWXlQ+Zz57Ol6Y1fBZkjVwU3qRJ7nhX//9K2T5zYPlUhH9ZxTJC0zIjA==","shasum":"143d9d16f0f3c625858c58324d8b29dbde7af135","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.4.1-g1d6980d.tgz","fileCount":50,"unpackedSize":626377,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgZH+aCRA9TVsSAnZWagAAssEP/1UwULnPCi5ol5kkegb5\nbIN9Xv0ECwDWcCw2SgjxKAeCR4tzgORy+xPiWnbhHUNkjJHJKVJhOxrQNHzc\nYzqtKbZsXjDhH/rqwXgzR7nROCuTRgJ9m1VAdQIPBj7CjO+nZIgEAtckuJCO\niZXy3OTwGEt/ldEtdm4LPC5F3V4EJn9db36w9CeoGerkC5GVb8DEh43WQhpN\nXu7Z3ewhiICUq+bRP9dAr8NvQaPh3NfeaM8dEW4Sph0Wgr80vPaJiC6lmJ/Z\nujN+8L/cm+W55bFIiCxoItcaB4b77b2FA9vrlGTtdyUar4xGIHsaRICyca1u\n+9ez1bu0KipetX8gC1Mzb1JMkXPuTS4rS466hvYJ1E+tLtCyjUxCpshzo5rJ\nQAIjabmikDtc1FwLFvkNTsFohCmE5R0YmFU+lDP86hc2RmItFLYE90gtjoEa\nTiuWHaYsSftvxBdkd+4RDSC31sD/T8DiKPcTEpYegCxSGJHl/MELnybD99DG\nQ8y9DF/qunHtTKaeKTaoGAL3DF6m0lPo9c2+d9ymABG8vs2K/AtT8lfMxTIJ\nR4uzvbvlOpb+lPyPpn5pD23dPfZyD5I7gDuiVtL1YVTciDEnIHlxRngYcNTv\nFymKvslPkCb5xUps+b+gSPcPBtWwtKuepHA0v0pYyRE0GaQpneCIfogzq0J4\nW0bw\r\n=PFSm\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIAlXSIhJa0nw0ofGd2T+FI+m2FB4Y/IdYhEyQSz2qQl/AiBBW+MhuTHMLP72DyDYl6cCxVQYJnWrYa/mBLphhlaWzA=="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.4.1-g1d6980d_1617199002179_0.48624218974695244"},"_hasShrinkwrap":false},"15.4.1-without-cli":{"name":"restful-react","version":"15.4.1-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [API Versioning](#api-versioning)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### API Versioning\n\nThe generated file will include an exported constant `SPEC_VERSION` that will contain to the OpenAPI `info.version` property's value.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"7f1f69b358a248a9a55fe58f5717622bc1d304ad","_id":"restful-react@15.4.1-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-ahmntDwvj6PmdznhWC0A4GjYvfY+ZmaetZvPSriFzIpVY+4zJigDwu8K/K4IXLZkOiT3tkv6RpQ7GOMe/x/lSQ==","shasum":"c863c36e804928348ceaccf41b22a42b5731dba4","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.4.1-without-cli.tgz","fileCount":49,"unpackedSize":569854,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgZKxjCRA9TVsSAnZWagAAGUoP/iSH/JemL4hcpjfSXYD+\nkOWKoinivSkLSBPaHkxKMyYN55RpcYI1yI5S8RgD++8CJKxW3pj2xvf/2B/J\nI41t6cQOPlIizQiv5qhCjHfQTMZFz8dc65Gj02T+Tj+XdBBGUXRFJ2t4gow4\nINMy9Gt/Av09AZKp35kIcbFQUEpXjarxSwEnzgxFbusA/O30FKo/IbcjlPhu\n0GvLxi3jXg0cvc7bgZiYKr/qg1HbsmOTwBVDwyDxiwTJ4ErPDMj4+5XGXU1Q\n0UGNXsDxU5VvwVjyutEZSLadHMYjzla12zNA9jKvM/i+UMoUNL1zCT0DVKlJ\nu/L67pxPhPaCg6zcwssokCF7arsHo4D/LlL1/SXLxL3TNs+uRE8z7/MLcQPt\nJS6U4BKkzuLFYXh6J3RfciA6i+6/iCNlznJT7CSlGTTFUNHm1jwKa2q2Dfdj\nAXTng+QRnpMhibCSLSyWHDkFfJYI4i4lnQNV+sz+BC+PLWtFpBRK13voXbhy\nOoJsMj3LM7cQOkceP/8hpgi0lbT3OFhw3qwcrMGyoIEywYAS2ARPZm2Ybjf+\nRgTOQHOuKJChMn1mopoxlWQLuyBCQDpSUfLnJVZG3h+SwuzJsoN7sU/xD8/P\neq+TVRfitx3ma7AnEPRRA0y1HbWRvZsBsBHMdT8VQ9xh/czosdp1OcCaRvb+\nU0Nm\r\n=jZmH\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIHXeaQ5GRv8xGlUsbzQYID8ufoU8ob2t8365jDzXPo8mAiAG5DqAKsjxOVv9kUA04ziZpbk4ixPljdt4b84LnavaXQ=="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.4.1-without-cli_1617210466649_0.7425576025385969"},"_hasShrinkwrap":false},"15.4.1":{"name":"restful-react","version":"15.4.1","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^2.1.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"7f1f69b358a248a9a55fe58f5717622bc1d304ad","_id":"restful-react@15.4.1","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-fnt4/A0izFxglbuE2NMe4NtfK7sVhQnftuVweN7TKhYG27PH9BDGQxwpaAA0B1PL2ipa2H5dlxI/tRIp5GnnKg==","shasum":"988cbf45ee59934e89ad23b7bf64c67d1647fa11","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.4.1.tgz","fileCount":62,"unpackedSize":627510,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgZKxtCRA9TVsSAnZWagAAigcQAJCGYmdIDqNr2fM1Nbn7\nFg3Vx8I/M81bMIukjf+BxslYclGhVsl+zPUnIlpEvvCyHCx5VWQIKWaJOVvE\nJpQz1fX1uWkKuxzTd4ld2pDJjuahL1qwj0ETDM8tvK4y6PT7fOm+S6uELerX\n7CX4ECD1d+fGX7JYgp5n4tby1DXDFnm1wC/V+yAVPLjdGxm4/KpWgs9yK/IN\n1kJAHScXqoP6NIFnpIMtirbvNLMxaSP9gy+Qe17PfFpyRmqPe3ef/pz0ORqc\nabWiUd406krgYBJF8izMY01XXWT9OhS6+zE9zIfmyJyYw4DK6q4KIFMv+TTp\nzt9ZEoQ7agFYJMuwdMhiG0tVUOlkHby6dK4YbFuNAxjMyazs0+PVc/WCXtXK\nsM0WyJZUOszl/5Q49Iisnxxf83RU0Wj2Ggob+fRZdyPsYx5sp5l/wd+p/tl8\nPIN6FIVaUfwpWh68HRkI8asVoiB5X7jbfQsTviV9Air24BScbXNDAiONKccC\n2xRmRl3ijaRlLT3CmqW/48ESp8nY00Tqwoy31psuqncVTCuPUcWaPnfiody1\njORAr7H+oyhdQpkYS2KYxYxBNa4KRV/Pw5vKqHKYEIR28iBdb4RQZZqdeQ41\nQQ3PcnE6nqGGmUpSI5yUalboOPux5mAD7PEF6vCTPYzbOe8+gFpIiwhPT1s1\n27m/\r\n=YlwV\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIDYrvzKknYXrKFLD5gp7alhNXkj0ZYwn1D51GQSu84I7AiBwATTATwAE1aDOur0wAKM/ckP3AUrffYSRrEDjmQT3cQ=="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.4.1_1617210476819_0.4720339915701637"},"_hasShrinkwrap":false},"15.4.2-without-cli":{"name":"restful-react","version":"15.4.2-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [API Versioning](#api-versioning)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### API Versioning\n\nThe generated file will include an exported constant `SPEC_VERSION` that will contain to the OpenAPI `info.version` property's value.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"1ae33fa9fb0b6bd4702577b20efb74dc928db1aa","_id":"restful-react@15.4.2-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-JdYijAPnzJOl0VIYAHt2NAmiqRgt8cKuJKyEvnMTs5ZJvCOVvba/+BW6UiA9kXYW69uLAzWkg2OLY1eA3x8sLg==","shasum":"bca526e8c447d3e5119b79352068bfda9af43b81","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.4.2-without-cli.tgz","fileCount":49,"unpackedSize":572497,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgeb8uCRA9TVsSAnZWagAAm/0P/1nr7+yK37My80DJV5T3\naMgQfjKQEgPKtK+9BzbeJfdGuVwPS5qRhFSPY5OvtS4+ymF5yny8ZpNA1V7r\n1JN04+LxS/0B/IivzalU5U/4ety3GCvb9By8/h1WLqwTHDqp3Z7sp8k27tw4\nFyEzeW08iRIxhAhd3GV6nppqOdOx/UCCs0Ow044o6RNwMCjR1zefKWG7//NA\nSk0Zb9IEV3mFjsQx8N8xmTIF2YWMxDG/CI3X1+GBI2zXOk3xH6TBSAiQy9Sq\nUeOcim2gkLbfSKA52izJImcvgGQge/8HL/R+Q9oIQnZ03XwQDm3dnU5B7ifh\nW/CMtwQ3Lr1niEgAVz2n1Vitl+f8R6QWFYgAcNg6ikihsArB1CygOGyOB4RO\n7/xKaMyNDPhAAOSYOeqpXfYG/nZguWdOjc2H8wBz/+Vw3nAUgStYwcmGlF7a\nKBxuu8wXkHRKq5ihhhdocbMLKHSAqBqZVtJvfymxlNt6UyT9KdUDWAh87Qh9\nRd/AbCBCFd2RiNPIKeij1wvZLGZkC1kiTc3zF4dSPISxiBxmnXEmHqe4+c7X\nBQG5d5akno2E5avX8TM7n3qoMINGPbHJqnzjxp2yu5Xfk/d9TFul51cYvOmx\nkmaLxgTwcCBEXvPmaCnK0w/JbbgRh7tHtCs52iAKw19IEcd2SiCin8x+tiSu\nUn0K\r\n=wvNk\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICUwXYwIm7I99XxfiHfFgAX/RTcV3LR5wILD8mPvWxlTAiEA67M7b1B5Vy0zem6TkY91Gwvvtfv6G1GwxlX+zcMvVIE="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.4.2-without-cli_1618591534192_0.6083806893316388"},"_hasShrinkwrap":false},"15.4.2":{"name":"restful-react","version":"15.4.2","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^2.1.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"1ae33fa9fb0b6bd4702577b20efb74dc928db1aa","_id":"restful-react@15.4.2","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-g88d/1bwGzZDLWMAoJ6+MYDk7nyuRgbKSItr+xKGmVHhaEBHCVLOhKGshQ91ATLOVRtspYXHsYBWnwLsLy+xsQ==","shasum":"f1f6d008317526846ace061ee4de93bd8c9f50a9","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.4.2.tgz","fileCount":62,"unpackedSize":630153,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgeb84CRA9TVsSAnZWagAAcb0P/jsKdX5TLJwbPhWLxxQ0\nAnlWc/hvAXGEvYB9FMY9qEqw3OrosR7lfzmOnqLA2JWXfAUXo891oCvydnId\nnKshw1iqLVpDnIiG35q5rqTlWWFESTq51Lvkvt+fjZC/r/SG/y/wRWiVWvqn\nQ/tEbfWDrojRzTq/qisK6KY1QwX7yioy23sTWt+NGyeyQjEAb9ttN0OH8gSk\n/HRtrvlS4RT11FIOnTYvwYA93QIDQ3EpUYgUEKABEAKlEJdnuPW2WcmybG7Z\nv5lyRhac/dsmr+0FoFD9F8Tn4yN8ThPTYvimFwyxOEQWCAKs+2HrJeFdO11Y\nxiKPv5uuLCHcSKkykLYNSmx4TA2UMUmttdQ1pLL5vC7Xcj+psRM3dv8/kZTV\n0UDeaF/UTdxP3bhsxqiIrsKGU9F+wY4egKoTnQG3By/N7O5y3FpWxn3aCgMK\n18LeXHi+VJ+aJxKVMSuF03Jg0ra+D/bVyCc7oqs7iLb3+x/qj8Sx3vI1oum+\nQDW17m3nr8mRRJzFOwNiL/1U28ldrloYBnlS7pYzyd0jSq6k2YFd5rCpoaka\nrdaBD+m4LqwsbjBwW1A9ApBudIDB2RolVCJ6JhIwVI4RIn3IaytLq02nyDKF\nxers+oTENU0FiHhVOjJftHSBZwer63cIJ7BDL7/vVCaU4EWqiYbVvHEPQZuq\nF636\r\n=Gf04\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDLgzquOdIh9/qyFY9qMul1FbaZTVKv3Kf8YSURPaD/SgIgSvQQYVcAcT6qjkNA4yFL0yKDFm8wt0cnBHcskWyiJlY="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.4.2_1618591544058_0.9892152638922049"},"_hasShrinkwrap":false},"15.5.0-without-cli":{"name":"restful-react","version":"15.5.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [API Versioning](#api-versioning)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### API Versioning\n\nThe generated file will include an exported constant `SPEC_VERSION` that will contain to the OpenAPI `info.version` property's value.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"9388e57bfb13f3fcc82c2aa4c3d2544a23e37aba","_id":"restful-react@15.5.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-o59KB0B3FntirS/TCq8Tc+cLbcI5PnCbTk0qeDc1/y7YARThqHalflvfbQoQ0snM8fUz4OcpDYWlxGFGgb0Kwg==","shasum":"e856a95332c1686d9ccd09f68273e728afe133a0","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.5.0-without-cli.tgz","fileCount":49,"unpackedSize":579715,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJggSXpCRA9TVsSAnZWagAAOP0P/3gleLcYZxxbd7jZfPEA\n6vDLpdb2odAItQLL4d+kKjupn/3EXEd62A3C4YNE4ELT4rBxiZZIxx/Qfc+h\nYh48QRHvCdaw0CIcIQP8MvmvR2VNlMKGMp42Sw55+PwZYMRSoCW8FvhKFwLV\n8RtRntCIGF6484MumGdFGz1zcNimMTD+lE6ECGLvXpAIrgRQznqryyLVSA25\nxxJMMY+6YQtO+eoKA6hpHUr7KWBMt53zROnB4L6JWb5rJgu6BPG9fIvzVpAy\noMuHrnqSJ4icwNO6K6taU7b+J82ZANlGfDJK0oWZcs7NrA3fqCCe/1Xp0m6T\n+uV8eEbX9FnM9XxkV4QV7sr98Dyr35U7e1i2uxufCuT5Iz1mGflvW0Yo1wx6\n0672jfPsBOGaqk4qph7htcisfTS/rouLtQCmICz8wNDUoaZbx/XRqHIL94yG\nkd9wi+w2St/TnaPYj03bg++rkdMYkVu/vLiDjf7n8a+wYPr4ngTBQSZdbpDs\n2UwfGa4uJ9EYf5cD7m7M248cwrWn/kAQtTIORLfgm9eUSBJ91DaWjE2WwOjF\ne29U+fS/JLwF/5zmaNNuwOupSoTdLHcgtTX4TzqYnyh/H5AXqMdaS8NopTBx\ni9166x1Oq3qaSeYSTWxQtG1o47wpOQUNxg4A2grsBs9Y0D4Wurq9swG7evdh\nwIwT\r\n=fgiS\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCBshkzGMmed5dchGb8VODLcEUoIEvL8N9EL6fqvrFmdgIgGpoiNl+L2kQnQgwkzPebf1rZQTeGnmtEoTspVApwOMY="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.5.0-without-cli_1619076585047_0.706235836792084"},"_hasShrinkwrap":false},"15.5.0":{"name":"restful-react","version":"15.5.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^2.1.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"9388e57bfb13f3fcc82c2aa4c3d2544a23e37aba","_id":"restful-react@15.5.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-3/8VU2o+p8tKYMaHfZAsT8OTqTQ8S+sxUmCTp5VLo4cVF+8vNXcr1xcWvkYXJoL2EoHkWpcr+YtheBtPYHoWjw==","shasum":"dcc7710bb1c9f50de70e6c476ed1a767064fca25","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.5.0.tgz","fileCount":62,"unpackedSize":637371,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJggSX7CRA9TVsSAnZWagAAhcAP/0OwNOyr37lwJjGDnGcP\ndVhi4icDbPyyTOb1uZpEHZMRoFan32NP58+p0c1Uha4RRIClnv7WIpZonUM9\nAhaBJQtYqMMcK+L/Z9lsVaUubQCJJ1cSMFWKlKTn7Lpl5AWozMTX5Vvel8os\nRVRHEcA8x+wLPPgTtNqhOXESNl6LTk32ZgRTnrPhPfbyyIYDAeLJdGPxaUw+\n99iPm/2MikZB19V9K4mhn7PCtX56Fh0aD2CZluQeAgd7nq/SoviKZMjQ0jlN\nkeYnv/xIXkr1vRSLcHRXBEsYEhTSZwrV9LRISkLW4NnVXXh2SVdeNKvIqgov\nx5bG8Z3UP5yaS98OupLfnRE1uLq3Lwq4aPDMMD0A42j/C6QMN43d5XsTTKrk\nWc7q8wtpZCb0qKHd4vW766fG62NcmcxymXGWnaWvEQRnKnA1dyInU5ExUshs\n95NFX6GWX2KEJjBfQsXoHG+GTUwQQTW70n0QRoMkbRO4B9Mrf40U7TbCD6Gt\nUWBwDAIxDQiRHNr1ODmJIWwJxx2sZHljwI8oe3bKn2pi4hFZjd+WYDjnVGKN\n80u3oe5vv4KsmZj/Mj5YvHY7eP4eGw5EPlQbsyCVh+CY3A55IAFgbn/ZI+jc\nRcZRkemL049QhmibgW7KZeYFOJHeKBIUjTqeqNZ8Zx3Tjnm3/baabN7Pv/CC\npi6q\r\n=wrz0\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIHfNiRzvoJEZIBOLrDs0PTv0yZo+4FfXCbay0Gw64YJdAiEA59Mi8BmO6xzSjeVuBxxnMNuKYmL3eLT9BVVGqaErfZQ="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.5.0_1619076602299_0.009946678453139013"},"_hasShrinkwrap":false},"15.5.1":{"name":"restful-react","version":"15.5.1","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^2.1.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"c910a47c1b8fe5a7f74b19c85f4e94e40bee286c","_id":"restful-react@15.5.1","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-cIEWmGEXkl/rb8Lsk7tAdv0mCH70Qt3oRhRj/hDXCUUiOkNBZf4iDjLM47qMBzRcFAFzYAI3QMSF46yK+nT/Eg==","shasum":"efd56c4c71227c4ed7f39a18c56f8a6bfc034379","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.5.1.tgz","fileCount":62,"unpackedSize":637790,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJggSczCRA9TVsSAnZWagAAdHMP/i5XGIa2EvZpZ3S9vXVZ\nmGo1Jz6SUQy6279Br7YHjBiLRCn4GI/ZdNRQr1LPc1sWwxwbEETwAOg0DyRo\nUnGaz3vOW7BPc1qEnc2gQi7eqKbmyG8n/cg6CerBqbrZ823b+r7aKoiDjGRZ\nlInKdzhufvlkdxZIokDwGGgDUq0WnGwlroY2zaYS6F1FbioQP7nBfTzkfC23\nmJyiDVanB4J0vTSpC03wQFFJ4LQYhYzti1STS5m5EgmXkesMkgKRskVEmEy0\nsVD3VV6Tbbhxkl75Wd79crYpodck7aor/bBzxn/NTGWMRfzf9FVeMbDXbx0V\n7J8bhK837UIk/T9V3af31HQRK2c+IhtaKt/EULsac62LvxALTR1xYFIeJLgy\nPziBTORyu7tr2KAVo+8EPw10yNbNC4te7D1EY9GST5tuDCA481K+9d7J5MFO\nXacaJecZmCJI+WaUWk9ZNrzsB2qXZ0/iBZJY3VuS4HbGDNMoF+8ao54kA1pu\nrh/VSzqmiErVV+L0PHvhdPSTeRfVprfQB301rIudTkyeRHnw/2mitzS3ahhc\npp19evNKxN66WbG0R3TxBfUGc8dv5p9yCISEA20hl9HgIQy8Qe5sgm0venUg\nHkmibHIU4ODZmzg7JrLmAwuDlU2KGQNUdcKYe2IooTzgGgOqAsXsZVq1bKyc\niyBx\r\n=16NC\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDEAdNAxqGuhepVZNoCPq7BBvvjM3NAXilPBSfrglPqiwIhAIG5gk6do8MJXmuIjNxvoLQuWawMg7WoV+kykJVG2urH"}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.5.1_1619076915165_0.10629230823938052"},"_hasShrinkwrap":false},"15.5.1-without-cli":{"name":"restful-react","version":"15.5.1-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [API Versioning](#api-versioning)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### API Versioning\n\nThe generated file will include an exported constant `SPEC_VERSION` that will contain to the OpenAPI `info.version` property's value.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your `node_modules` folder and _not_ committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.\n\n    **Caveat:** _Since_ your token is stored in `node_modules`, your token will be removed on each `npm install` of `restful-react`.\n\n1.  You're done! 🎉\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"c910a47c1b8fe5a7f74b19c85f4e94e40bee286c","_id":"restful-react@15.5.1-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-2YAXU2Cf9A2NsM/vi9lvQPk7DIFbHb/CTyUU8Q7t9hA6DlkpXRovresOMISt/kDxA6i7t9Vgw7NxpghB6gkHGw==","shasum":"c111142f6ed1c5d7e89ac6a18e18be557d28c3a9","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.5.1-without-cli.tgz","fileCount":49,"unpackedSize":580134,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJggSc7CRA9TVsSAnZWagAAMXQP/j8T0z2pROSsY4MGg9RN\nAIqx3B5LFOvhoxOa+d+FV0JatX304sGeMxrg06s1J2NPyyQ7fjDuZfDK3CuA\nAECa/7pfwYwaLXAcSmXAp1JjeN3kymphmrJXoH/YXbB4h4Ec2JRnDcKDo1q2\nKUlv8ceIJvE7NZOmAqumK0aqwzkwdjRjSZKOdC5JCRUI3wizGp+bWuZJuKlq\nnDxZmvHIFDdEV3eyQDXk6woKsIu+SqtizfrMv0PTNfP0NSw1R2WzLBmncT1D\nAwrqQjsHelzBpxvELJc0wdvceWEu+/OhsCsPgnkDMVob1pvyHIOZePyQ0ekw\nqu83u8aVDtFeDMK7WnN7cAUNl5UqG5WVsoyjk6qzxdlNRzgdiOcrzYN9jtD9\nLJO3kp0JiD0GRGCF2ZxAHHFQ2OM2hjEP4BYARHHrWNj1NKq80DaKN4jVGDGl\n53KUBdi3RUDSkEPuhUD6eHO2sGFd3U+627cO47OHqSIl5bTaztspjSgma0N9\nvA0dbJp9KAc9M0aQ1QiTNalTAn6+I8kFeNQs6atJ03sfqxcAvjL9G/sGmA+o\n+U5pyLVR3fWsx9+4ozR7TWosuqxlHgwO3HfXj4oeA+UHfRVuwyPTHscSw8t1\nv89u3fO5MqW+YGzhkucappHmFlmntpArCU4E1ElkPxJTTu6bl1TGncLKmHWv\n4uU+\r\n=ptp2\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIDumI4dE5NQd+YIH9+Qe9HfZpcHWCsKB/G8Qq2lf+nQ3AiEA5x44EgliRDxdW6mC9GpJlDvWrHF4MvZN+A16WeV3NHs="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.5.1-without-cli_1619076922382_0.5249642031076236"},"_hasShrinkwrap":false},"15.6.0-without-cli":{"name":"restful-react","version":"15.6.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [API Versioning](#api-versioning)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### API Versioning\n\nThe generated file will include an exported constant `SPEC_VERSION` that will contain to the OpenAPI `info.version` property's value.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your home directory.\n1.  You're done! 🎉\n\nNote: For CI environment, you can also provide the github token with the environment variable called `GITHUB_TOKEN`\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"f24fc89b910eef4b1610b9bc7e6ac92a99decde0","_id":"restful-react@15.6.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-ys3Rc6j8cDOH/a/UkDNaGhBlavoMzthQVpzOJrfANaPt0YWp3JsUuTSI2Gz+KtdJco22Z2MPG3ATNr/zqVoC4w==","shasum":"7cb29305e54a2199700ed099f9de70682c6e8a2c","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.6.0-without-cli.tgz","fileCount":49,"unpackedSize":580229,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgkk1iCRA9TVsSAnZWagAAC0MQAJgQNXzicLKOfz4OwbXP\nWfXru/Z6ZeoxJNS0c0XrqbtJBt8RHKS3xdhzA+3MhJFgO3VN4KujrVE10ohB\n1WhB2/pDQNabNLCiv0bCEaXgVhl84FLNyVzXodwXb9ZeN8Qc910DXE3LiinX\nYY3m0mxBaJrrkjy+PdjwIx0k+geXrQHRh/v4Z+LZEHPhO2UxVTDGys290XqD\n24nj5ygmA9flUHFc+yVwKvcUzbq0DCEAJ9nNh4kJ+4zg02AJHdN49nUGrlpJ\nbagfSo8Ho+GDvPbRZ+RSazpRQMLVH4RK8FVb55+x2pxkcEWf20WfiyfQRdms\nja8UGCOWQoNIMYG3tKzTfLpJ62NsP1HArnA29vbOO0JeoY+YS+5fyNdDi0QG\nnpXxKDA0Do6qecIzNJflB4tJllo7/eaAEAi3o8HwY28KLmcdtDuvO2YHzUfZ\nfMiPVAIWyKrLkdVTmBKn0JpXzznUApXiR6ZBzlAmSi4Ib7pqGKZb1igfqx8c\nKI/JCv5bNREXDCv/ckViGZ3oXYe9xuYDyFSnvOnMkvEuTlfE7ti3pjzd+ccz\nC+WIPUIC776jeSpXiM9H5oFQx0coXsmcFlcYv0+D0iErL6v/D7aFlelXZwCe\n44SvJVHdzIq0FUHHIFLM0T3dtbt4jY2qZE9dzRsssHmlVqsK7O8fALNh9hqD\nOBS9\r\n=rInj\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQD7VXYOGd9jCzWM3SbVrvA3Piev1EW4NsrEgtfRQXZwzgIgJJbXaEVf4DRYVRO85xgbmXY+0L+7La97qglJo2zRkIQ="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.6.0-without-cli_1620200802306_0.8217275417907357"},"_hasShrinkwrap":false},"15.6.0":{"name":"restful-react","version":"15.6.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^2.1.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"f24fc89b910eef4b1610b9bc7e6ac92a99decde0","_id":"restful-react@15.6.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-pwhJRdLpgjYelUwLoLeCNDHFZzPRw+7RApO1Rher+1c+aUk+bIDa3vJ9ZFLdnjTgHyI9kGIA8b+E3KIb9b8WZA==","shasum":"c0d690ea5cea3c5f59e8a85e01e0a6c27f960387","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.6.0.tgz","fileCount":62,"unpackedSize":638041,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgkk1xCRA9TVsSAnZWagAAGD4P/iQLuWM6I/YviNcC33j0\nECsLRwve31YHBzqv5wEjskacQ0CrCcgujsnhw6/GRud8W3Et01/BnrbGmkYB\nVUyINwl11E7cnnMpSbwEpZX9X7PW6AfBqkUaoZP/JcOvs+8/bhNOsqnZsSu3\nBKNvnXT0p977QMdg3FtXLl73tOxFOsr1nFozyCclGmgA3mo7VZnALWcPWNIo\n9hNkHkbLzl946Y1+OKc5m5ZAAnbBOSjHAcZ8J0JL6okG7kvHv9lvyvJDPwW8\np/BcbA8502pRihGmAEdBwdyCuJgVQazaSV1s8f572209XRDvDsBgyF8qdbzL\nsemHe+HWnyDhrCyRAuhiQeBfODeku8nKoOH5DNe0BpOntuyHVOQTaEAER0Y0\nIQLecZ0gbRs2ft0/IE3Tvp3vshc2/mII7sPNztGoBuTqpqKU/T6SHsh5WjGx\njBpcHOtoBcccM+Nqw3idIZV0cI4Z4cNZ7KYA+qh574+54waH/V25OIF+yrzN\nAGmjuSfMlS4SDLBNkG43QEbQwhUTuOaXVB17OJIQNXAEkuUYW3+6XvzdUXeT\nwHSgEJUqQ/Vsx/UAxrIbX3ZDuIZvxTrhuQ/tkH4iF+87ZOS+vTmfdQOiU+w9\nKQnyGZ7QzuolFwsthk++LCw43RfS7GTrM4BAAkll4dLAnklVM9cPb/8qZgZu\n3xQE\r\n=LJF8\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCmsD9n0MxXLv29vy7+mQiZAbGsY6GNGMmyjdTnju/NEQIhAOgdpOD0oRmVQNkC5WT0wwjC7P3lzguY406IB+tuMutp"}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.6.0_1620200817319_0.8019277419436361"},"_hasShrinkwrap":false},"15.7.0":{"name":"restful-react","version":"15.7.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^2.1.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"d14793b22ff02c4ba81452634fff32bcb519d4fa","_id":"restful-react@15.7.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-fCSWBlm2wdeBy2FyElZWCQBrSt5/1yMO5MIQRHFnWNpxvEudK41rU06blQSItHwi5ScPBYr0bkAZ31U9m81yAg==","shasum":"bf7992a01ed9436834d15ff80a08d50a75d2c167","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.7.0.tgz","fileCount":62,"unpackedSize":639247,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJg7YAbCRA9TVsSAnZWagAA+kYQAJSlp9GR/LfDJmIxRPoq\n9TisMNqkl2Xa7MsQ5srJdvJFs6y4CChm1DHUQQburjsl8L14TIhILFj9F2he\n9dJoKXn875kCPujnTjy8v7Gma3FTzu6Puto5Co9gF3vegwM5G7DFBVXKiul/\nYqbIQIsqbMKme1zLj1SxMcPnIjuw9Dfupgu2iqKzN4M8o7KqfAzRBsAl8xtK\n1J7sv71DaRyPCBIM4H+w++NeJsP23FN0Lqeox0VcPZomP00pOdU5AMggiYz3\nWlW+sRM0io0PnirIbCGrP6I7IilNhAyvgikLvJrziJnA4dy5/NOiu7ntCaM+\n8quGbgq5QlOJExnkr2iUt9QlIuxlHD2dRQSTWK1eVPDkb0Lyg7da3cMp2HNU\nv6JxMTcusO3UPpt68hvNWGXsXL0zW2Hs20Z25JUGE7snSZbLhBSYtUuyrbFh\nm7ZYHTtIOdBPWkMSCSOsCAoqwnbDi/rPf01dVZgjapxEGhv9kTlGJLmIdWcK\nlDP/LB6f9CAaYayTygqR441B9TZh8SbvQ6vf8AzuarPWFFx+dBnWzPUpxopa\nS7PV0tMrDHB//4Y9P+KEqbHB1Hd8rVRLgJKmQelv6jTJlZC60gkYPnYwHhzy\nFKR8XhFl9OiMcenq89D7+R/NLoJ8imCKOPg6kTB2ZQIy0p8AoYICb0fZapLD\neFS4\r\n=75Zb\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDbRFVWQYSd/cUZpuaMS1d0mxvZf6sl9n6xAcz1kAMsmAIhAOtrM700Et0gA7jFR8GcaHbAULAcx4RqQbZsFv0z3R0T"}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.7.0_1626177562895_0.15197694619993074"},"_hasShrinkwrap":false},"15.7.0-without-cli":{"name":"restful-react","version":"15.7.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [API Versioning](#api-versioning)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### API Versioning\n\nThe generated file will include an exported constant `SPEC_VERSION` that will contain to the OpenAPI `info.version` property's value.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n                [X] security_events\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your home directory.\n1.  You're done! 🎉\n\nNote: For CI environment, you can also provide the github token with the environment variable called `GITHUB_TOKEN`\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"d14793b22ff02c4ba81452634fff32bcb519d4fa","_id":"restful-react@15.7.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-ZmpnC9GUsL/fKueX7SY9mS/1iL+QdQv614r4H5ilgza75F+x9/vJMhj2IP98vVaTUniAue2RgfgsDXDx2wlytA==","shasum":"766d18e2907f272d18dbb3c2111b1f26743f34c3","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.7.0-without-cli.tgz","fileCount":49,"unpackedSize":581314,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJg7YAyCRA9TVsSAnZWagAA5vEQAKDcebh0WBBoryFhp3f9\n04vdA/89iFvDnq+X14JjTnwTkPQ/7VSBL4ICPtdJvNwxF+QSV8atj4eLZ0jH\nQCkFqX0P4YsscYZstbIHhTmtzhwJrhxXn6FXtErRUhN5Ce+6xM2R4iQeBCEu\nnESeLYgJ2H4B6xVOpnsQWRuWK02GBnsfqB+3iOAthrwa7fzaiJmeGvoyvEXc\ncLwFU9vBvVFeIGv4InR2qtTFJvS/aBpR8c+kDzN1q3I8ZQ+pLsp/NvPmB3uW\nQKX0cFlmEsDBkfiFhsSVVlMiamGjbq98MFfjWjsMhlhRY+x6PlNcjP1Yu5c7\nrVOKBDAnLefCeGWJjzNG1zb/9GOb9m1sYiuR+yItNO0eXEXK5lcU2jELXtfH\nYR43Cr6+ERlkum+oH2hEXSvWay6fs5xYLS51E+sanxbG0oluSSxtOW7MkpL5\nh5IwuyLOUHi2y1UR6trQu1w5CR8qqVwpOhYywyR6PekbQRfXPVLVjA0sfOpn\nt7FZEXxEqeJEobwgwFTZ2UyiFFTtiUQkM98ewLHzHPr4+3+THz5Ega+XkC8x\nFxCa2CM4w6YKHYJekICkZN3oGlDTcw19fMTAsizobpX/mkQXPDUtjxRISiuc\n7K0sVOfmci96sXgqpPFL0uJmpXWqY5BFYAmPrv8B2EVnxP6i5igV9m/WPh5H\ngMgp\r\n=UbHD\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCCFICpo2HDQEweEgDNNGbJqH4+d8SfE4Xcty7iO7wX+wIgJ5yWoKHIa+xjVqEDRfhEbTQgnKMZo92cHUcHg/69X20="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.7.0-without-cli_1626177585773_0.5279118334369435"},"_hasShrinkwrap":false},"15.8.0-without-cli":{"name":"restful-react","version":"15.8.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [API Versioning](#api-versioning)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### API Versioning\n\nThe generated file will include an exported constant `SPEC_VERSION` that will contain to the OpenAPI `info.version` property's value.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n                [X] security_events\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your home directory.\n1.  You're done! 🎉\n\nNote: For CI environment, you can also provide the github token with the environment variable called `GITHUB_TOKEN`\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"0f21924fe97bd0375d91a665534f2074fc3e3671","_id":"restful-react@15.8.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-rVHedk7fhQHhISMJLpuMQN6/MhsgYXKDKvGUC6V+ET/9FMmN9cHo0+hR7AbXSG9uoDK+tEUUqSHWty8Rlq0STw==","shasum":"e1b402951deb1b402a5c2b56f24a369c5a811426","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.8.0-without-cli.tgz","fileCount":49,"unpackedSize":581817,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJg9twGCRA9TVsSAnZWagAAfDUP/0RUw4I5oEfL6BX4/di8\n8SVM5ywGbcXGsCl68LaaDUw+0pETQBK0OVWcHlyLEFxqecAUSKwGGq1mgFtQ\nNepZ7/qY5Pm60dzU5rn6ZPVfHJu28OXzmx9CnHrLBFLvgPi4U5eoh+PwmYTa\nwrwD7i2ZW9uzFTDquFO6SsgAlY8dGNVNN/Ewyb017/TkI8Km+BMlqFAsttAW\nInVPDhzXEWsyWf7HD5qXDDkonLSm4b9C06g/g8XLVNCbu10pop4LOw9NP4Lv\nVIfVOuS0t0IZMAmjm4jWi8lZ4sCXMz9ctvyvjXYzYJTEMbNL5qFsXze++pPx\nHYSCfnFpi0CaDkt0R3pfkaCzdWILbyNaT493P3bMyNuoUk8qW7K8VZcNjaWV\n8C3EuNHn36O6yYVgKfbUiAMX4S7D2VtiwntWDGMcb8y3p1hZmPdhtNN/TKQ2\nq4BnpVwPUda2FmcySWF1xgT72Mxyr/hxO4rbk0MbpPI6la76rvCFmtDBY3Tk\nVgL6IadFGZfcT/xSNGlZyT7dycyZyv7+sLNK4jPfLVIBgu0/qshw8loD/ysY\n6y4DWSedkgHZouGJvRHfLGbo8wggifVzHR0Wi4PTRvQ925rg6B+nCfBuKo9O\nGVhC0xNXRpBt/g/Rnm0WqW6/cKlH6aofgRKdZTAiWTKlPgTXkIi+TFJStczL\nqlpe\r\n=Pv9P\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICSrehW1MAYYhCVeQbvQbSNg5kvYNbFt6G0ZLLnhuSZrAiAO+/RrBYJP9ZNFYpJsylzk3y29+Ik6b93WOrc4MHoIzA=="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.8.0-without-cli_1626790918147_0.30280642254146706"},"_hasShrinkwrap":false},"15.8.0":{"name":"restful-react","version":"15.8.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.16.0","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^2.1.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"0f21924fe97bd0375d91a665534f2074fc3e3671","_id":"restful-react@15.8.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-ENtpRA5vEZgTUndkuNK+G20lNVlDS2X8VeGkR87H+fWBk2scLhbQuGQM2QGqB6gBfBTiYR4QkYf6LJO9CKVSXg==","shasum":"4aa84137e136547bfe00ad598a6b4fc40ed81c5b","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.8.0.tgz","fileCount":62,"unpackedSize":640631,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJg9twXCRA9TVsSAnZWagAAwUcP/j+uppJ0swdl8AhRZL7c\nmD4yS7WrrqsO0peBGnbLyNxdbbrmLb0I2OHFDcDS5dEcNaTHBtCdM16Qel5D\nAObOP6QSkI3eAjoi0/1cGYO//2Rr1B26735m2IC4dqA0z9My8d+eLHp91ylU\nTvRpUGm7/00WQyWwOowovEVbM+wZpChLP0WWsr7Lfj7YXX+0Bu0rtKQNlPNH\nN2X+yjAAj3iVhBxjxTelFlEpIuumcyEmm8LsYQBAehmly9QMLzbqMViVF5fg\nOWB0fFtF60V7zewlhBVib8I5g/Kwp5galXzz9A9Qzgvm4i8kajTv3kkSqY1f\ntiEFekPK5hkhgwYmcTHdURzmo2Trxx99bnenNxqpcVPYQmhFfEpbRp0jJuJC\nLmd/hth0ktkt8gvwyIXVYf7w5PoOh9v4/qkiywEDtO49cmH5BP4c7MKFBHVr\n7k1GXbGkAMbjOja35CnN0sndahL6lYRkG+R5O+sHn6pbjfSNHzNKMsUlEujS\nkm3mFEBUvmGSd+xSoUeFm/q7kki8dwvVBQU/PWTSedFmK5Y5ad7oAKWR9yz2\nxkzg1rNu7Fgopa7Ha2YMUScQHM2W4oqrHRuF9RUvSozOaGc1SSMmlEh9ztzU\nASNpECGL9oI2rl4InvzzJeCnfRNndPRfFo8i1C7ivZHTHYGzGygQgPmpjtX+\nWqmy\r\n=ytwR\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIByHTFaCTXYojOeLacTlYwWlhJbgCY2uNCfZaNEdD/mkAiEAxUgR1744+2ChWyJHermOJDHEF4WqOrcnavZo6N1o2NM="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.8.0_1626790935185_0.5103892990497148"},"_hasShrinkwrap":false},"15.9.0-without-cli":{"name":"restful-react","version":"15.9.0-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [API Versioning](#api-versioning)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### API Versioning\n\nThe generated file will include an exported constant `SPEC_VERSION` that will contain to the OpenAPI `info.version` property's value.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n                [X] security_events\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your home directory.\n1.  You're done! 🎉\n\nNote: For CI environment, you can also provide the github token with the environment variable called `GITHUB_TOKEN`\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"15f04ca9b721035a67b21747e7e050b5d4867af3","_id":"restful-react@15.9.0-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-sPzllphAUgLGH/KCJdMTQjxym0mHPowlwF/7cj1lL1T8+tWqtbZjeKNWIe+sNtsqjjET9m2/sWdyTXkJxZPwWQ==","shasum":"94dd283b4f05405812c67a8a60c03e281540e091","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.9.0-without-cli.tgz","fileCount":49,"unpackedSize":582051,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJhGkutCRA9TVsSAnZWagAA5jwP/1352izwJsqBEciT0RhX\nKS6z4gk/G4G7C1erGT5jPDDwguKm1KyGN4X0hVgfYY940fw6eiJmycoXD6/F\nlARM5GVGhynELNSk4Qm+dKq1HUW5Sv7y1t8+sqnX/8wVfutYXHzR2eanBqK7\nRN7JMFvdr0YPbW228+aJccBDRnxNqDuCDrGhEfcXEo1rvKB1En3lnvq1rerM\n48nwFl9q5vMLFh4MsefznxnkSadtLora8qFCALgQcnwCNvZ1CthyhLNyeB7O\nFV3qEAJS7AZHapyB+hbcQv16tfpeqrJXq70Yh1xzk2refFXOQaGcq43Kr2Cd\nCa3qtS5cSBHkGDrwMlv582TaD5Kf/w50BydxBYFPjsDryS4p2L2faHLbnZM7\nHVzxc3mNTFXCYJrwswlInS1ezzK4lkQO2pCV/W+mn8o6reW/9l6vdCU8a9W2\nqpWPFfMMKZllikwhE4KdX1vHuJF/Yja+sPLsxRZ5udTVRpiB9kaeeYQw1rL/\nEWifgQ+YrGqE0V9AYKMOe9wWu0+vMLxK3LQBOoCxfefQVcRI5tSBjJVDBLdt\nCLEvmoFCq+pF65LKNMugc4mmB1fFXDLPDNN5P5hPbhQqEdnF5uPsaP1WYbSZ\nwrg8OSO58J/Y0HUIVPRgiosdnvDL00cpRyOOmr71Ybw2mikUUdk5xoUSFOdA\nkVqQ\r\n=ob1R\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIDMlRM0Q1FGQ7+Dvij81qfmLUCT5ZI8DGI200T+IcIgSAiB3BRUUaiwY0rchpVmbtyXRlcvNVO31z3paUA1LbBXflg=="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.9.0-without-cli_1629113261699_0.25006525087226894"},"_hasShrinkwrap":false},"15.9.0":{"name":"restful-react","version":"15.9.0","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.46.4","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^2.1.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"15f04ca9b721035a67b21747e7e050b5d4867af3","_id":"restful-react@15.9.0","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-lBH2x1A6HstwgsZabcgwgBpNd/SCoivjEmZsJ4vyild0Ppcq17Tvl/iQjyokKPmUlegUrP30lkB9jvUolPCysA==","shasum":"8e0bb44d4b4cb8aaa53e4c6cb23335955da7b3d1","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.9.0.tgz","fileCount":62,"unpackedSize":640865,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJhGkvKCRA9TVsSAnZWagAADIgP+weCtf1lJU/EtQDBwjHi\nH+hkvlJ3yYyyvA8ud269xYcxAD+WYvCuabZ4vacVIhnYzbCFC/AOSGDvRdbJ\nxUfpkdySO9W27ve5T4WPjzRjIxtSebOB6BRheME+cLzreHPdL394p0Jh8DWJ\n1jA3KlPu4zr7ZxD5siIo5LkiiJjMOb/QnA8D+BpM8i5LkcDWZeLxSx/nO08v\nQy6CAB0zz9ZOEvCpZdoAJH4poJa4AbXW3JIroHBKMYKaBQwPYMgZ++CkJStT\n02I/qBLw5FbHa21qIwJkS2DJ+LmjmKhgB/YfzwzVvs4lIosDYkbYQPo66q3h\ncd1IkPcPzvpmnxe8GkegMIjr25iCV9+d410C22Ae+y/8xUgsYKrXC+BMTEav\nZom3I8S4GOCF2FvDTeoH5RSvI5PdNLc1ytaLQRoFfdFwzB3PEdbT9AgDF+gN\nwojJ3QCJEsWLP0AvpG0c4Jf09lBHZpgRzCSxN9YZoPVWIgA5sU+X1YemoTZ6\njMprJ34lU/ub98FPS1Bv0zSV/tyCIY8BVM27C9Is2HZBEKegG1rQm+ux8QsM\nhGzjettmJKtcHnYComD/YeZb0QU8VCydXrlr5ZNpoqoGFErAPQRzZvMFbmO1\nMwa1gLGGKxNkbl+FaIHoP2NPNRD+cCRztdztbNk2OccjC7rSZLfcphybi+pN\noFfh\r\n=/Sp9\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIAsqnWQRKG9PcytqG8qGxYSSanEBib0gcwlZSpd4AdUGAiAxL8ed4/w3kJnC5sTzfoQ7uM4xjLKYZA4cnnuOOXnyrw=="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.9.0_1629113290773_0.9943657133988937"},"_hasShrinkwrap":false},"15.9.2":{"name":"restful-react","version":"15.9.2","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.46.4","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^2.1.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"cf9912c9e52fd9e159bc33954f22f3a68eaa9345","_id":"restful-react@15.9.2","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-N9JZVIyH7y8YcdKfkK4gTA9Z8hYITHI8zcKXpMnafA/05uaEKd1FsWOTPf6BsHi0Pw1kkbcGbN9wSj86j/WGCg==","shasum":"fffefceeefd1eb68afc7febc55061522d7e5916e","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.9.2.tgz","fileCount":62,"unpackedSize":640136,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQC8UvY+pZP9cMzbAolwpDn746EXDiE+t7nSooG1gE/tJAIhAInu29be8MRw1vEisV6uE1OCh9UdAypUlXQA1eSCbVOH"}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.9.2_1632440481776_0.46364365046301437"},"_hasShrinkwrap":false},"15.9.2-without-cli":{"name":"restful-react","version":"15.9.2-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [API Versioning](#api-versioning)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### API Versioning\n\nThe generated file will include an exported constant `SPEC_VERSION` that will contain to the OpenAPI `info.version` property's value.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n                [X] security_events\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your home directory.\n1.  You're done! 🎉\n\nNote: For CI environment, you can also provide the github token with the environment variable called `GITHUB_TOKEN`\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"cf9912c9e52fd9e159bc33954f22f3a68eaa9345","_id":"restful-react@15.9.2-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-eXJwByLusuMYT7UkcbTAonRQIsvQdHUoPRitNsgaH32O5o0wDLLle0pnA4+MffsPMJmf+P4HdVWs6OLHLXO5wg==","shasum":"cd308028c38e86bfd2fbec5ee74afd62737a494e","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.9.2-without-cli.tgz","fileCount":49,"unpackedSize":581274,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIFqDjt9mvVp0msCW4tMiKL7sVgTI8KHrpe//eDxdxovSAiA06+G77ghYC5twIFV3wbu3wusuhwWc5L6sgCbX+quUag=="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.9.2-without-cli_1632488679927_0.7798001614893819"},"_hasShrinkwrap":false},"15.9.3":{"name":"restful-react","version":"15.9.3","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.46.4","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^2.1.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5 || ^17"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"c77e52eed0fbe59c755d8dca04b6f1214cced8d7","_id":"restful-react@15.9.3","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-Eda9UyHgcsmO5GLmw+qprfeaHh5LgGlK4X+IWRZG/s45PM8/LXVfVz/3Y+46Z3kTugex9TmUKH0z9D8LacK7eA==","shasum":"93731a2171b837554d504101e0580bc94702fc7c","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.9.3.tgz","fileCount":62,"unpackedSize":640455,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJhqeixCRA9TVsSAnZWagAAWQAQAKHiuSF6pJbmoS/GIgUZ\nF25cNOXAOAGMAAk1jh8K4GVbidx4WgClFonOQuexMewfNBu5aNRtZKI5Fczl\nbCTdjFZMiAw1FWjNHQo6kKboj7hUJiwUKr06zdWXOpRGem+q34QYIqwLJ8K6\nlWPbhE9rTczc/9uRnjPXPINBNyvgTN61QgVv2I/sw+6N5Kt9is83attd3OP8\n2OtrBUw+TUvGCTb5uqjpiFIdhObw88KD3HC1sTebu/RJQ8rc2akVKTt+tawp\nOu6BsN28TYtnHldlUGfTzp78g/Vfz9yW/tqRsB1NwLJfTk0f9dQkDzsoEoNp\nIhZJ3ZucJPcsnz/Ma0BekminbiBaZbDj8+iUK9GFm2zxLHYjVN7i5DMCSsE8\nYfYIx6nHvceRy0pqB9hOyvBK2iT5b3Jefj1GdoZKXqCoDZHIZJsUBM0okK6y\nITVU7bDNuUrsac5+T5rngyeMLKHfhhhByTjdXWWxAhy8HVP+qQdzDIpNKFte\n1+6KgSmJci5juddhES3A4EDQh5Bh7YwAmpT1lSKG28trXPYi3nVxxRVEbWOy\nWv3+TNz5RUyDDRBziNkfjyzeAJJGT2hKFJKh5xzRpQRLotP3kMdirPjHzgkO\nuVSA8zXKqd0V+UlxJieiEXrtyk9aK4BcP8mJpPHOx0iDU+YC93HyP53ezH8k\nxGTu\r\n=B/yl\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIHQuFmI2yYNQzFgh7iyGHkWV1hEqigKIe4QXzkVELZIkAiEAhJ+CLSWS/2RqjsVRxsZoRDtn1qGIbwcBA5xGeYAljaA="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.9.3_1638525104801_0.5092139244925171"},"_hasShrinkwrap":false},"15.9.3-without-cli":{"name":"restful-react","version":"15.9.3-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5 || ^17"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [API Versioning](#api-versioning)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### API Versioning\n\nThe generated file will include an exported constant `SPEC_VERSION` that will contain to the OpenAPI `info.version` property's value.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n                [X] security_events\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your home directory.\n1.  You're done! 🎉\n\nNote: For CI environment, you can also provide the github token with the environment variable called `GITHUB_TOKEN`\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"c77e52eed0fbe59c755d8dca04b6f1214cced8d7","_id":"restful-react@15.9.3-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-n5KWJGYSrYbldFu9eYH8eHNimmF7ACoMdGRIEqigB0bdqRGvmZoFHCemfgkDaT36b3oH2G5Ai2LFGtloszk5nA==","shasum":"1860273bd4cce1982d8c684e2a225f62e59a15b9","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.9.3-without-cli.tgz","fileCount":49,"unpackedSize":581593,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJhqei1CRA9TVsSAnZWagAAvnAP/3cOUK02+DdTxP940R1W\nZYXhbqJCD66qveEqRcUhffbMmKSogclyAkj8ju2oZMEVle9V9UnyeQlnO2Ig\noR4rtOXhGcL3yhrlGj6SIgpG/aJ3QsrZd9I6OKu7L7/DAa3r5J942cZlALqx\nvl5JVypMqiE36OI8SKCkXxDVrmrhWWk6OcSVqdJU+yLLVvpEY6spzBiAlbxY\nX0cHDdgzgNxfnGmW7fWZVeGeATpRZzaFwTAVwY1RxWbE22VjGOfzJQoI8Cad\noprTu3L/iwbCfD+qPlX6k3NaHkPNy0u6BqB5aFevvfcsR0UGZw6Q3vmBAUN5\nZ9SVX1pvTgnLjzkH2DYUQn+6eR7W9fDL/x/QofDxIq7dLSYx9LqDU7sXVhqa\nwCGkRGp3iWFOr7ccj4wYqzuSxfLRKdgwT93ip3V2GsfP2Iez8bDh76zpmnIV\nULAlDYWHO1rFwdi5XWdltm+NnOJ5fVYbYMS8YZcuBy60NeCTsPbpYowDajxk\n62wTLzax3WvwOWU+N0+tqPRZq33yHjy5hEFDpNL7A0NAa0wmtlKlUUE8VO/I\nXDLc5yjXlYrjezZuYY4sBkv6+GyZxO8OLxLOvj6dmqaCYpHjeTEf8oXvcj2X\nZw5x5W02kdDZ2ElRZ1tnb16Xp0TlzuLokCBZ6QRZ96tc6gmcMNCnkmFnpz1Q\nZk32\r\n=wGYt\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIHydhVxLHIKR51U4gW245JZ6weEquOHHDgPne/1AwpzhAiA84sPMJyJh6LZkBbrbl4M0mSGJFaY73udmNOUX+9P0Hw=="}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.9.3-without-cli_1638525109679_0.7724712955511304"},"_hasShrinkwrap":false},"15.9.4":{"name":"restful-react","version":"15.9.4","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bin":{"restful-react":"dist/bin/restful-react.js"},"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"scripts":{"start":"tsdx watch","test":"tsdx test","lint":"tsdx lint","build":"run-p build:*","build:project":"tsdx build","build:bin":"tsc && rollup -c rollup.config.js","postbuild":"rimraf dist/**/*.test.*","version":"auto-changelog -p && git add CHANGELOG.md","examples":"run-p example:*","example:github":"node dist/bin/restful-react.js import --github OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml --output examples/petstoreFromGithubSpec.tsx","example:url":"node dist/bin/restful-react.js import --url https://petstore.swagger.io/v2/swagger.json --output examples/petstoreFromUrlSpec.tsx","example:file":"node dist/bin/restful-react.js import --file examples/petstore.yaml --output examples/petstoreFromFileSpec.tsx","example:advanced":"node dist/bin/restful-react.js import --config examples/restful-react.config.js"},"dependencies":{"case":"^1.6.2","chalk":"^3.0.0","commander":"^4.1.0","ibm-openapi-validator":"^0.46.4","inquirer":"^7.0.3","js-yaml":"^3.14.0","lodash":"^4.17.15","lodash-es":"^4.17.15","openapi3-ts":"^1.3.0","qs":"^6.9.1","react-fast-compare":"^2.0.4","request":"^2.88.0","slash":"^3.0.0","swagger2openapi":"^5.3.2","tslib":"^2.1.0","url":"^0.11.0"},"devDependencies":{"@testing-library/jest-dom":"^4.2.4","@testing-library/react":"^9.4.0","@testing-library/react-hooks":"^3.2.1","@types/chalk":"^2.2.0","@types/commander":"^2.12.2","@types/inquirer":"6.5.0","@types/jest":"^24.0.25","@types/js-yaml":"^3.12.5","@types/lodash":"^4.14.149","@types/nock":"^11.1.0","@types/node":"^13.1.6","@types/qs":"^6.9.0","@types/react":"^16.8.8","@types/react-dom":"^16.8.5","@types/request":"^2.48.4","@types/yamljs":"^0.2.30","auto-changelog":"^2.2.1","doctoc":"^1.4.0","husky":"^4.0.7","isomorphic-fetch":"^2.2.1","nock":"^11.7.2","npm-run-all":"^4.1.5","prettier":"^1.19.1","react":"^16.8.5","react-dom":"^16.8.5","react-test-renderer":"^16.8.5","rimraf":"^3.0.2","rollup":"^1.29.0","rollup-plugin-typescript2":"^0.25.3","tsdx":"^0.12.1","tslint":"^5.20.1","typescript":"^3.7.4"},"peerDependencies":{"react":"^16.8.5 || ^17"},"husky":{"hooks":{"pre-commit":"tsdx lint"}},"gitHead":"aabfa722d8f6395fb0ae7142f39ab91ceabfefce","_id":"restful-react@15.9.4","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-rrC68KMGVZ0GDxLfQR+6tbmUPL5rX1mni4GOzPVMsO9XFew2BWK107pZTi9z7UrFO7LElGOWaKMZrikyIiendQ==","shasum":"7c39f496165a252b26f479e7909ef40782ac5117","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.9.4.tgz","fileCount":62,"unpackedSize":640510,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJhyj35CRA9TVsSAnZWagAA+U4P/RpzJmi6oqZAkU99/0br\nzzRAVh0jmEDTz6lrbBFRANuBn463t4e5KCqU3hAksoqtozCoX8wCv+N7NscV\nwl2hv3SyAPO9m09j+sz2Fxn8p/TjWujKbzNI1yJ5WEJyduvrj7X4r5BtprBq\nHyjqBAEObDHO7Joy4+6VuVjRcgUWb9JA8qzutI5fHu8Ewer1zW8CViqpij5A\nKRBf0vWGth5DyR502zIYe0j9H+rw1/qYnbVXLhdjGYKyDGxuYUVnZ9YcyUpa\nlq6gCUleNH5yUHCJzx3WG7u719E6JhTF2dQbxsQYUu5W3OeqhyZXVrPPAdn3\nkAyEwIqkjzYW/5JtAcVqioCPlHbJ8cCH+y7jhbsQCQszdy27f1Szd56wx78k\nDwZV+d5I9Ukwr+/fAZlC3DWSrFWcjhsCyf9fhFWkV2I+Q8ZaAdOCAokPEtS9\nlJarhzG+c5R/NOCNMEalL9FX4OUOp/074LA3dnNgWi9neE99mhYZbgQTRrfm\nyQpsbsEr5ldlLxWoCyAJ4vjB2AufPYp3FcFOI/ShsiqTOip7vZLf3dJJMVwL\nhQgBnFTAd8wts0ob936lRD5LIcGfR3HugbNjWIcOB/AK+Q63opHG+YN3gcdh\nyjlOto6N49xnUehuMUc0niKhVGfEOLzxTqjQDgHzBrFG/lw0x+8mhvr2B+Kj\nFfmV\r\n=pi4S\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDEe1gT4X5gPRlxEX1x6IeRRtY5S6HD1z9Zs17VFo/y7wIhANuo+vDXdFGlv3CW37JsgNPWo3c71565ysdQu4ijh9Fs"}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.9.4_1640644089533_0.44405052569668446"},"_hasShrinkwrap":false},"15.9.4-without-cli":{"name":"restful-react","version":"15.9.4-without-cli","description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","keywords":["rest","restful","react","react-component","fetch","data fetching"],"homepage":"https://github.com/contiamo/restful-react","bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"main":"dist/index.js","typings":"dist/index.d.ts","module":"dist/restful-react.esm.js","repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"dependencies":{"lodash":"^4.17.15","lodash-es":"^4.17.15","qs":"^6.9.1","react-fast-compare":"^2.0.4","url":"^0.11.0"},"peerDependencies":{"react":"^16.8.5 || ^17"},"readme":"# `restful-react`\n\n[![npm](https://img.shields.io/npm/v/restful-react.svg)](https://www.npmjs.com/package/restful-react)\n\nBuilding React apps that interact with a RESTful API presents a set of questions, challenges and potential gotchas. This project aims to remove such pitfalls, and provide a pleasant developer experience when crafting such applications.\n\nIt can be considered **a thin wrapper around the [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) in the form of React components and hooks.**\n\nWhen used in a setup with [OpenAPI / Swagger](https://en.wikipedia.org/wiki/OpenAPI_Specification) specs and [Typescript](https://www.typescriptlang.org/), **restful-react ensures a reliable and always up to date contract between backend and frontend.** It generates components and types from your specs and can be integrated quite comfortably into your development workflows (featuring for example the import of OpenAPI specs from your github repos).\n\nrestful-react is **very well tested, production ready** and powers all of our projects at Contiamo.\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Overview](#overview)\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Global Configuration](#global-configuration)\n    - [`RestfulProvider` API](#restfulprovider-api)\n  - [Loading and Error States](#loading-and-error-states)\n  - [Lazy Fetching](#lazy-fetching)\n  - [Response Resolution](#response-resolution)\n  - [Debouncing Requests](#debouncing-requests)\n  - [TypeScript Integration](#typescript-integration)\n  - [Query Parameters](#query-parameters)\n  - [Mutations with `useMutate`](#mutations-with-usemutate)\n  - [Mocks](#mocks)\n  - [Polling with `Poll`](#polling-with-poll)\n    - [Long Polling](#long-polling)\n    - [Full `Poll` Component API](#full-poll-component-api)\n    - [Polling and Code Generation](#polling-and-code-generation)\n  - [Code Generation from OpenAPI / Swagger specs](#code-generation-from-openapi--swagger-specs)\n    - [Usage](#usage)\n    - [Validation of the OpenAPI specification](#validation-of-the-openapi-specification)\n    - [API Versioning](#api-versioning)\n    - [Import from URL](#import-from-url)\n    - [Import from GitHub](#import-from-github)\n    - [Transforming an Original Spec](#transforming-an-original-spec)\n    - [Advanced configuration](#advanced-configuration)\n      - [Config File Format](#config-file-format)\n      - [Config File Example](#config-file-example)\n      - [Custom generator](#custom-generator)\n      - [Only generating custom code (no react hooks/components)](#only-generating-custom-code-no-react-hookscomponents)\n- [Contributing](#contributing)\n  - [Code](#code)\n  - [How to publish to npm](#how-to-publish-to-npm)\n- [`@without-cli` npm package](#without-cli-npm-package)\n- [Next Steps](#next-steps)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Overview\n\nAt its core, `restful-react` exposes a [hook](https://reactjs.org/docs/hooks-intro.html), called `useGet`. This component retrieves data, either on mount or later, and then handles error states, loading states, and other cases for you. As such, you get a component that _gets stuff_ and then does stuff with it. Here's a quick overview what it looks like.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nand on React Native,\n[Edit restful-react basic demo on Expo](https://snack.expo.io/SJaSAj49r)\n\n```jsx\nimport { AppRegistry, Image } from \"react-native\";\nimport React from \"react\";\n\nimport { useGet } from \"restful-react\";\n\nconst App = () => {\n  const { data: randomDogImage } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n  return (\n    <>\n      {randomDogImage && (\n        <Image\n          style={{ width: 250, height: 250 }}\n          source={{\n            uri: randomDogImage.message,\n          }}\n        />\n      )}\n    </>\n  );\n};\n\nAppRegistry.registerComponent(\"react-native-app\", () => App);\n```\n\n## Getting Started\n\nTo install and use this library, install it by running `yarn add restful-react`, or `npm i restful-react --save` and you should be good to go. Don't forget to `import { useGet } from \"restful-react\"` or similar wherever you need it!\n\n## Features\n\n`restful-react` ships with the following features that we think might be useful.\n\n### Global Configuration\n\nREST API endpoints usually sit alongside a base, global URL. As a convenience, the `RestfulProvider` allows top-level configuration of your requests, that are then passed down the React tree to `useGet` hooks.\n\nConsider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\n// index.js\n\nimport React from \"react\";\nimport { RestfulProvider } from \"restful-react\";\n\nimport App from \"./App.jsx\";\n\nconst MyRestfulApp = () => (\n  <RestfulProvider base=\"https://dog.ceo/api\">\n    <App />\n  </RestfulProvider>\n);\n\nexport default MyRestfulApp;\n```\n\nMeanwhile, in `./App.jsx`,\n\n```jsx\n// App.jsx\n\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage } = useGet({\n    // Inferred from RestfulProvider in index.js\n    path: \"breeds/image/random\",\n  });\n\n  return <img alt=\"Here's a good boye!\" src={randomDogImage && randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\nNaturally, the request will be sent to the full path `https://dog.ceo/api/breeds/image/random`. The full API of the `RestfulProvider` is outlined below. Each configuration option is composable and _can be_ overridden by `Get` components further down the tree.\n\n#### `RestfulProvider` API\n\nHere's a full overview of the API available through the `RestfulProvider`, along with its defaults.\n\n```tsx\n// Interface\nexport interface RestfulReactProviderProps<T = any> {\n  /** The backend URL where the RESTful resources live. */\n  base: string;\n  /**\n   * The path that gets accumulated from each level of nesting\n   * taking the absolute and relative nature of each path into consideration\n   */\n  parentPath?: string;\n  /**\n   * A function to resolve data return from the backend, most typically\n   * used when the backend response needs to be adapted in some way.\n   */\n  resolve?: ResolveFunction<T>;\n  /**\n   * Options passed to the fetch request.\n   */\n  requestOptions?: ((url: string, method: string, requestBody?: string) => Partial<RequestInit>) | Partial<RequestInit>;\n  /**\n   * Trigger on each error.\n   * For `Get` and `Mutation` calls, you can also call `retry` to retry the exact same request.\n   * Please note that it's quite hard to retrieve the response data after a retry mutation in this case.\n   * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component\n   * to deal with your retry locally instead of in the provider scope.\n   */\n  onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;\n  /**\n   * Trigger on each request.\n   */\n  onRequest?: (req: Request) => void;\n  /**\n   * Trigger on each response.\n   */\n  onResponse?: (req: Response) => void;\n  /**\n   * Query parameters passed to each request.\n   */\n  queryParams?: { [key: string]: any };\n  /**\n   * Query parameter stringify options applied for each request.\n   */\n  queryParamStringifyOptions?: IStringifyOptions;\n}\n\n// Usage\n<RestfulProvider\n  base=\"String!\"\n  resolve={data => data}\n  requestOptions={(url, method, requestBody) => ({ headers: { Authorization: authToken } })}\n/>;\n```\n\nHere's some docs about the [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) type of request options.\n\n### Loading and Error States\n\n`useGet` hooks return an object with loading and error states, to allow for state handling. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n  });\n\n  return loading ? <h1>Loading...</h1> : <img alt=\"Here's a good boye!\" src={randomDogImage.message} />;\n};\n\nexport default MyComponent;\n```\n\n### Lazy Fetching\n\nIt is possible to use a `useGet` hook and defer the fetch to a later stage. This is done with the `lazy` boolean property. This is great for displaying UI immediately, and then allowing parts of it to be fetched as a response to an event: like the click of a button, for instance. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: randomDogImage, loading, refetch } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    lazy: true,\n  });\n\n  return !randomDogImage && loading ? (\n    <h1>Loading!</h1>\n  ) : (\n    <div>\n      <div>\n        <h1>Welcome to my image getter!</h1>\n        <button onClick={() => refetch()}>Get a good boye!</button>\n      </div>\n      <div>{randomDogImage && <img alt=\"Here's a good boye!\" src={randomDogImage.message} />}</div>\n    </div>\n  );\n};\n\nexport default MyComponent;\n```\n\nThe above example will display your UI, and then load good boyes on demand.\n\n### Response Resolution\n\nSometimes, your backend responses arrive in a shape that you might want to adapt, validate, or restructure. Other times, maybe your data consistently arrives in a `{ data: {} }` shape, with `data` containing the stuff you want.\n\nAt the `RestfulProvider` level, _or_ on the `useGet` level, a `resolve` prop will take the data and _do stuff_ to it, providing the final resolved or unwrapped data to the children. Consider,\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet } from \"restful-react\";\n\nconst MyComponent = () => {\n  const { data: imageUrl } = useGet({\n    path: \"https://dog.ceo/api/breeds/image/random\",\n    resolve: image => image && image.message,\n  });\n\n  return imageUrl && <img alt=\"Here's a good boye!\" src={imageUrl} />;\n};\n\nexport default MyComponent;\n```\n\n### Debouncing Requests\n\nSome requests fire in response to a rapid succession of user events: things like autocomplete or resizing a window. For this reason, users sometimes need to wait until all the keystrokes are typed (until everything's _done_), before sending a request.\n\n`restful-react` exposes a `debounce` prop on `Get` that does exactly this.\n\nHere's an example:\n\n```jsx\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n    debounce: true,\n  });\n\n  return (\n    <div>\n      <h1>Here's all the things I search</h1>\n      <ul>\n        {data.map(thing => (\n          <li>{thing}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n```\n\nDebounce also accepts a number, which tells `useGet` how long to wait until doing the request.\n\n```diff\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: true,\n+    debounce: 200 /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\nIt uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) function under the hood, so you get all the benefits of it out of the box like so!\n\n```diff\n\nconst SearchThis = props => {\n  const { data } = useGet({\n    path: \"/hello/world\",\n-    debounce: 200,\n+    debounce: { wait: 200, options: { leading: true, maxWait: 300, trailing: false } } /* ms */,\n  })\n\n  return <div>\n        <h1>Here's all the things I search</h1>\n        <ul>\n          {data.map(thing => (\n            <li>{thing}</li>\n          ))}\n        </ul>\n      </div>\n}\n```\n\n### TypeScript Integration\n\nOne of the most powerful features of `restful-react` is that each component exported is strongly typed, empowering developers through self-documenting APIs.\n\n![Using restful-react in VS Code](assets/labs.gif)\n\n### Query Parameters\n\nAll components in this library support query params (`https://my.site/?query=param`) via a `queryParams` prop. Each `useGet`, `useMutate` and `Poll` instance is _generic_, having a type signature of `useGet<TData, TError, TQueryParams>`. If described, the `queryParams` prop is _fully_ type-safe in usage and provides autocomplete functionality.\n\n![Autocompletion on QueryParams](assets/idp.gif)\n\nPlease note that the above example was built using our [OpenAPI generator](#code-generation) in order to infer the type of component from the specification and automatically generate the entire type-safe component in a _very_ quick and easy way.\n\n### Mutations with `useMutate`\n\n`restful-react` exposes an additional hook called `useMutate`. These components allow sending requests with other HTTP verbs in order to mutate backend resources.\n\n[![Edit restful-react demos](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/restful-react-demos-vjets)\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\nconst ListItem = ({ id, children }) => {\n  const { mutate: del, loading } = useMutate({\n    verb: \"DELETE\",\n    path: `/posts/`,\n    base,\n  });\n\n  return (\n    <li key={id}>\n      {loading ? (\n        \"Deleting...\"\n      ) : (\n        <button onClick={() => del(id).then(() => alert(\"Deleted successfully. Pretend it got removed from the DOM.\"))}>\n          ❌\n        </button>\n      )}\n      &nbsp;{children}\n    </li>\n  );\n};\n\nconst MyHugeList = () => {\n  const { data: posts } = useGet({\n    path: \"/posts\",\n    base,\n  });\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {posts &&\n          posts.map(post => (\n            <ListItem key={post.id} id={post.id}>\n              {post.title}\n            </ListItem>\n          ))}\n      </ul>\n    </div>\n  );\n};\nexport default MyHugeList;\n```\n\n`useMutate` is strongly typed, and provides intelligent autocompletion out of the box, complete with other available [HTTP verbs](https://developer.mozilla.org/de/docs/Web/HTTP/Methods).\n\n![Mutate](assets/mutate.png)\n\nEach mutation returns a promise that can then be used to update local component state, dispatch an action, or do something else depending on your use case.\n\n### Mocks\n\nNo backend support yet for your amazing feature? Need to isolate an edge case? You can easily provide a mock to `useMutate` and `useGet` to bypass the classic flow.\n\n/!\\ If `mock` option is provided, no requests will be send to the server. /!\\\n\n```jsx\nimport React from \"react\";\nimport { useGet, useMutate } from \"restful-react\";\n\nconst base = \"https://jsonplaceholder.typicode.com\";\n\n// Mock the `mutate` handler\nconst { mutate: del, loading } = useMutate({\n  verb: \"DELETE\",\n  path: `/posts/`,\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    mutate: id => console.log(`The item ${id} was deleted`),\n  },\n});\n\n// Mock the `loading`, so it's easy to isolate the loading state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    loading: true,\n  },\n});\n\n// Mock the `error`, so it's easy to isolate the error state\nconst { data: posts } = useGet({\n  path: \"/posts\",\n  base,\n  // This will avoid any server call in favor of mock response\n  mock: {\n    error: \"oh no!\",\n  },\n});\n```\n\n### Polling with `Poll`\n\n`restful-react` also exports a `Poll` render props component that will poll a backend endpoint over a predetermined interval until a stop condition is met. Consider,\n\n```jsx\nimport { Poll } from \"restful-react\"\n\n<Poll path=\"/deployLogs\" resolve={data => data && data.data}>\n  {(deployLogs: DeployLog[], { loading }) =>\n    loading ? (\n      <PageSpinner />\n    ) : (\n      <DataTable\n        columns={[\"createdAt\", \"deployId\", \"status\", \"sha\", \"message\"]}\n        orderBy=\"createdAt\"\n        data={deployLogs}\n        formatters={{\n          createdAt: (d: DeployLog[\"createdAt\"]) => title(formatRelative(d, Date.now())),\n          sha: (i: DeployLog[\"sha\"]) => i && i.slice(0, 7),\n        }}\n      />\n    )\n  }\n</Poll>\n```\n\n`Poll` supports:\n\n- an `interval` prop that will poll at a specified interval (defaults to polling 1 second), and\n- an `until` prop that accepts a condition expressed as a function that returns a boolean value. When this condition is met, polling will stop.\n\n  The signature of this function is `(data: T, response: ResponseInit) => boolean`. As a developer, you have access to the returned data, along with the response object in case you'd like to stop polling if `response.ok === false`, for example.\n\nBelow is a more convoluted example that employs nearly the full power of the `Poll` component.\n\n```jsx\n<Poll path=\"/status\" until={(_, response) => response && response.ok} interval={0} lazy>\n  {(_, { loading, error, finished, polling }, { start }) => {\n    return loading ? (\n      <Progress error={error} />\n    ) : (\n      <Button\n        loading={editorLoading || polling}\n        condensed\n        icon=\"ExternalLink\"\n        color=\"ghost\"\n        onClick={() => {\n          if (finished) {\n            return window.open(editor.url);\n          }\n          requestEditor();\n          start();\n        }}\n      >\n        {finished ? \"Launch Editor\" : \"Request Editor\"}\n      </Button>\n    );\n  }}\n</Poll>\n```\n\nNote from the previous example, `Poll` also exposes more states: `finished`, and `polling` that allow better flow control, as well as lazy-start polls that can also be programmatically stopped at a later stage.\n\n#### Long Polling\n\nAt Contiamo, we have a [powerful Long Polling specification](docs/contiamo-long-poll.md) in place that allows us to build real-time apps over HTTPS, as opposed to WebSockets. At a glance the specification can be distilled into:\n\n- Web UI sends a request with a `Prefer` header that contains:\n  - a time, in seconds, to keep requests open (`60s`), and\n  - a **polling index** that is a server-sent hash `ahpiegh`.\n  - all together, the client sends a request with a header `Prefer: wait=60s;index=939192`.\n- The backend server responds, either with:\n  - an empty response with status `304 Not Modified`\n  - a successful response with data and a new **polling index**.\n\nThe polling index allow the client and the server to stay in sync: the client says \"the last stuff I got was at this index\". The server says \"oh, let me get you up to speed and send you a new index\".\n\nVisually, this is represented as below.\n\n![Contiamo Poll](docs/long-poll-flow.png).\n\nTo get this functionality in `restful-react`, this means specifying a `wait` prop on your `Poll` component, provided your server implements this specification as well.\n\n#### [Full `Poll` Component API](src/Poll.tsx#L53-L101)\n\n#### Polling and Code Generation\n\nBy default we generate a `Poll` component when the `prefer` header is specified in the OpenAPI/Swagger specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling).\n\nWe do not generate an equivalent hook version. Polling is quite trivial in a react hook, so we usually just use `useEffect` when we need some polling feature.\n\nExample:\n\n```ts\n// Poll data if no completedAt\nuseEffect(() => {\n  if (error) {\n    return onError();\n  } else if (data && !data.completedAt) {\n    const timerId = window.setTimeout(() => refetch(), 1000);\n    return () => window.clearTimeout(timerId);\n  } else {\n    return;\n  }\n}, [data, refetch, error]);\n```\n\n### Code Generation from OpenAPI / Swagger specs\n\n`restful-react` is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.\n\n#### Usage\n\nType-safe React data fetchers can be generated from an OpenAPI specification using the following command:\n\n- `restful-react import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx`\n\nThis command can be invoked by _either_:\n\n- Installing `restful-react` globally and running it in the terminal: `npm i -g restful-react`, or\n- Adding a `script` to your `package.json` like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n+       \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\"\n      }\n```\n\nYour components can then be generated by running `npm run generate-fetcher`. Optionally, we recommend linting/prettifying the output for readability like so:\n\n```diff\n      \"scripts\": {\n        \"start\": \"webpack-dev-server\",\n        \"build\": \"webpack -p\",\n        \"generate-fetcher\": \"restful-react import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx\",\n+       \"postgenerate-fetcher\": \"prettier FETCHERS.d.tsx --write\"\n      }\n```\n\n#### Validation of the OpenAPI specification\n\nTo enforce the best quality as possible of specification, we have integrated the amazing [OpenAPI linter from IBM](https://github.com/IBM/openapi-validator). We strongly encourage you to setup your custom rules with a `.validaterc` file, you can find all useful information about this configuration [here](https://github.com/IBM/openapi-validator/#configuration).\n\nTo activate this, add a `--validation` flag to your `restful-react` call.\n\n#### API Versioning\n\nThe generated file will include an exported constant `SPEC_VERSION` that will contain to the OpenAPI `info.version` property's value.\n\n#### Import from URL\n\nAdding the `--url` flag to `restful-react import` instead of using the `--file` flag will attempt to fetch the spec from that endpoint.\n\n- `restful-react import --url https://api.mine.com/openapi.json --output my-awesome-generated-types.tsx`\n\n#### Import from GitHub\n\nAdding the `--github` flag to `restful-react import` instead of using the `--file` flag allows us to **create React components from an OpenAPI spec _remotely hosted on GitHub._** <sup>_(how is this real life_ 🔥 _)_</sup>\n\nTo generate components from remote specifications, you'll need to follow the following steps:\n\n1.  Visit [your GitHub settings](https://github.com/settings/tokens).\n1.  Click **Generate New Token** and choose the following:\n\n        Token Description: (enter anything)\n        Scopes:\n            [X] repo\n                [X] repo:status\n                [X] repo_deployment\n                [X] public_repo\n                [X] repo:invite\n                [X] security_events\n\n1.  Click **Generate token**.\n1.  Copy the generated string.\n1.  Open a terminal and run `restful-react import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx`, substituting things where necessary.\n1.  You will be prompted for a token.\n1.  Paste your token.\n1.  You will be asked if you'd like to save it for later. This is _entirely_ up to you and completely safe: it is saved in your home directory.\n1.  You're done! 🎉\n\nNote: For CI environment, you can also provide the github token with the environment variable called `GITHUB_TOKEN`\n\n#### Transforming an Original Spec\n\nIn some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:\n\n```bash\n  restful-react import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js\n```\n\nThe function specified in `--transformer` is pure: it imports your `--file`, transforms it, and passes the augmented OpenAPI specification to `restful-react`'s generator. Here's how it can be used:\n\n```ts\n// /path/to/my-transformer.js\n\n/**\n * Transformer function for restful-react.\n *\n * @param {OpenAPIObject} schema\n * @return {OpenAPIObject}\n */\nmodule.exports = inputSchema => ({\n  ...inputSchema,\n  // Place your augmentations here\n  paths: Object.entries(schema.paths).reduce(\n    (mem, [path, pathItem]) => ({\n      ...mem,\n      [path]: Object.entries(pathItem).reduce(\n        (pathItemMem, [verb, operation]) => ({\n          ...pathItemMem,\n          [verb]: {\n            ...fixOperationId(path, verb, operation),\n          },\n        }),\n        {},\n      ),\n    }),\n    {},\n  ),\n});\n```\n\n#### Advanced configuration\n\n`restful-react` supports the concept of \"schema stitching\" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, `restful-react.config.js`\n\nTo activate this \"advanced mode\", replace all flags from your `restful-react` call with the config flag: `--config restful-react.config.js` (or any filename that you want).\n\n⚠️ **Note:** using a config file makes use of all of the options contained therein, and ignores all other CLI flags.\n\n##### Config File Format\n\n```ts\ninterface RestfulReactConfig {\n  [backend: string]: {\n    // classic configuration\n    output: string;\n    file?: string;\n    github?: string;\n    transformer?: string;\n    validation?: boolean;\n    skipReact?: boolean;\n\n    // advanced configuration\n    customImport?: string;\n    customProps?: {\n      base?: string;\n    };\n    pathParametersEncodingMode?: \"uriComponent\" | \"rfc3986\";\n    customGenerator?: (data: {\n      componentName: string;\n      verb: string;\n      route: string;\n      description: string;\n      genericsTypes: string;\n      operation: OperationObject;\n      paramsInPath: string[];\n      paramsTypes: string;\n    }) => string;\n  };\n}\n```\n\n##### Config File Example\n\n```js\n// restful-react.config.js\n/**\n * Restful-react configuration.\n *\n * @type {import(\"restful-react/dist/bin/config\").RestfulReactAdvancedConfiguration}\n */\nmodule.exports = {\n  myFirstBackend: {\n    output: \"src/queries/myFirstBackend.tsx\",\n    file: \"specs/my-first-backend.yaml\",\n    customProps: {\n      base: `\"http://my-first-backend.com\"`,\n    },\n  },\n  configurableBackend: {\n    output: \"src/queries/configurableBackend.tsx\",\n    github: \"contiamo:restful-react:master:docs/swagger.json\",\n    customImport: `import { getConfig } from \"../components/Config.tsx\";`,\n    customProps: {\n      base: `{getConfig(\"backendBasePath\")}`,\n    },\n  },\n};\n```\n\n```json\n// package.json\n{\n  \"scripts\": {\n    \"gen\": \"restful-react import --config restful-react.config.js\",\n    \"gen-first\": \"restful-react import --config restful-react.config.js myFirstBackend\"\n  }\n}\n```\n\n##### Custom generator\n\nTo support even more advanced usecases (like a promise base API, mock generator or anything else that can infer from your specs), you can define your own template in `customGenerator`. This function will be call for each route with some useful computed values (see the types above) and the resulted string will be added to the generated file.\n\nYou can see a concrete usage inside the `examples` folder and try yourself in this repository with the following command:\n\n- `yarn build`\n- `yarn example:advanced petstore-custom-fetch`\n\nYou can inspect the result inside `/examples/petstoreFromFileSpecWithCustomFetch.tsx`\n\n##### Only generating custom code (no react hooks/components)\n\nIn some cases you might want to use the familiar restful-react to generate code for non-react environments (e.g. promise-based fetchers for nodejs or other frameworks). In this case, you can disable react code generation altogether by passing the `--skipReact` flag or, if you are using a configuration file, setting `skipReact: true`.\n\nWhen set, only your custom generators will be executed.\n\n## Contributing\n\nAll contributions are welcome – especially:\n\n- documentation,\n- bug reports and issues,\n- code contributions.\n\n### Code\n\nIf you'd like to actively develop or help maintain this project then there are existing tests against which you can test the library with. Typically, this looks like\n\n- `git clone git@github.com:contiamo/restful-react.git`\n- `cd restful-react`\n- `yarn install`\n- `yarn test --watch`\n\nFrom there, you should be able to start developing without problems.\n\n### How to publish to npm\n\nJust update the `version` in `package.json`!\n\nAs soon as your branch will be merged to master, a new npm version will be automatically published for you.\n\n## `@without-cli` npm package\n\nIf for any reasons you don't want to use our CLI to generate restful-react components, we provide a `without-cli` version of the package.\n\nJust `npm install restful-react@without-cli` to have this light version.\n\nThis version will follow `latest` but without the cli part (more details into `publish-without-cli.js`).\n\n## Next Steps\n\nWe're actively developing this at Contiamo to meet our use cases as they arise. If you have a use case that you'd like to implement, do it! Open an issue, submit a Pull Request, have fun! We're friendly.\n","readmeFilename":"README.md","gitHead":"aabfa722d8f6395fb0ae7142f39ab91ceabfefce","_id":"restful-react@15.9.4-without-cli","_nodeVersion":"12.16.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-KWsRJBs7lrDVGPr+sK0j2g0SRLwP8MwY4id4iOkFZZakt4FRBdxvrakr0lYgHifsdiHtT85puEqxLYBLBGLUpg==","shasum":"d1222d1e76912bdb9f78a5e4c87f60aa622883f4","tarball":"https://registry.npmjs.org/restful-react/-/restful-react-15.9.4-without-cli.tgz","fileCount":49,"unpackedSize":581593,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJhyj4ACRA9TVsSAnZWagAAZxgP/isPGidZT4Eh3mSNp9x7\nwGGn6jQih+gxGIVuZloDmn+Vcrsp0NetaW3DF4eu60xbePPdptGJaapPEu+F\nC3o1QboZDN+zb5S5iA0TXTMDxEtDP0su+UzHUFirabxAn8e+ck2gBskRlkUC\n5ajXkzNJ/At2O36zhFcj6DZpxib6Y3u88gU07wCPs3QbMn5KRdA8FtwDC/ee\nMky4Dd17dXMlH/IJzdvx52ARjpVhgW1Xv25QahfEuCYAIIwhBbamcmjZLiP1\n+CyfkrQ2wsGpDfzTXprPuXTzSFQzMgDKP+uP/va1Lvpf9MHLL2cd47fCwmGS\naBxUMwQ79NplWLxDXI+/W/7PmAbrP6659e1o75Ft8AMTPPbnE6APzTIr5kQm\nAP3Emh0zHQklLU3Xc8MbSy7uH/dyQkwJZJVSVZhwfk9mXmsyvvbUEND1v76t\nC+THGVgzUNahGm4gn2Q9RuLTh1gLsbCXLx9q7ezGIj5T6Typ6l6suzAy1H0X\n8S7luV0GDjzkZGnp071LwAVBXrR6FFx/DxgXsaU1j07/VFmW4Ii5zNs34FQ6\nXl1lR2ERUg4zBeehUDUWlernuXDAndWC5e470Q2FndvGNiQMQas7bg8tfk7v\nud/vLl0nFfBuBMOVW/CSs7oN9yrhRjLiEv9bLlezlw+8SR13wHlcag5qji+z\nrbDx\r\n=mLCB\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDPu6w+2rltKxozGWNoVp2RB3GJODPow4ZpFSq8x8FF7wIhAObNDj59/NPNchPY1xEeS4K6rsolSNsTn7h3XYVb0nOe"}]},"_npmUser":{"name":"fabien0102","email":"fabien0102@gmail.com"},"directories":{},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/restful-react_15.9.4-without-cli_1640644096215_0.2734877793059445"},"_hasShrinkwrap":false}},"time":{"created":"2018-07-02T16:22:49.713Z","3.0.1":"2018-07-02T16:22:49.773Z","modified":"2022-05-15T21:55:15.839Z","3.0.2":"2018-07-02T16:44:59.065Z","3.1.0":"2018-07-06T15:52:47.193Z","3.0.3":"2018-07-09T22:13:45.833Z","4.0.0-1":"2018-07-10T10:25:07.093Z","4.0.0-2":"2018-07-10T10:39:00.186Z","3.0.4":"2018-07-10T10:40:55.741Z","4.0.0-3":"2018-07-10T10:41:50.426Z","4.0.0-4":"2018-07-18T13:34:06.488Z","4.0.0-5":"2018-07-19T14:30:54.564Z","4.0.0-6":"2018-08-01T12:39:00.854Z","4.0.0-7":"2018-08-03T16:58:37.572Z","4.0.0-8":"2018-08-06T13:53:27.818Z","4.0.0-9":"2018-08-08T08:22:36.687Z","4.0.0-10":"2018-08-08T13:34:56.403Z","4.0.0":"2018-08-08T14:31:03.768Z","4.0.1":"2018-08-14T09:12:39.123Z","4.0.2":"2018-08-27T13:30:06.078Z","4.1.0":"2018-09-05T08:52:39.732Z","4.1.1":"2018-09-05T09:09:03.526Z","4.1.2":"2018-09-05T09:27:35.650Z","4.1.3-0":"2018-09-10T10:49:21.963Z","4.1.3":"2018-09-10T11:00:02.601Z","5.0.0":"2018-09-10T11:55:02.628Z","5.0.1":"2018-09-10T14:07:56.587Z","5.1.0":"2018-09-12T11:26:52.924Z","5.1.1":"2018-09-13T01:11:16.045Z","5.2.0":"2018-09-13T22:21:36.373Z","5.2.1":"2018-09-25T03:31:18.080Z","6.0.0":"2018-10-31T14:31:43.733Z","6.0.1-1":"2018-10-31T17:24:14.688Z","6.0.1":"2018-11-01T13:04:40.079Z","6.0.2":"2018-11-07T13:48:21.866Z","6.1.0":"2018-11-13T13:40:27.505Z","6.2.0-openapi-0":"2018-11-19T15:29:02.097Z","6.1.1":"2018-11-20T09:43:25.339Z","6.2.0-openapi-1":"2018-11-23T13:44:47.258Z","6.2.0-openapi-2":"2018-11-23T17:37:22.055Z","6.2.0-openapi-3":"2018-11-23T17:49:12.076Z","6.2.0-openapi-4":"2018-11-23T17:52:50.376Z","6.2.0-openapi-5":"2018-11-26T14:48:56.768Z","6.2.0-openapi-6":"2018-11-27T10:02:25.370Z","6.2.0-openapi-7":"2018-11-27T10:17:56.126Z","6.2.0-openapi-8":"2018-11-27T16:10:17.603Z","6.2.0-openapi-9":"2018-11-27T16:56:48.364Z","6.2.0-openapi-10":"2018-11-27T17:07:32.083Z","6.2.0-openapi-11":"2018-11-29T10:27:33.976Z","6.2.0-openapi-12":"2018-11-29T11:16:14.877Z","6.2.0-openapi-13":"2018-12-03T14:32:40.975Z","6.2.0-openapi-14":"2018-12-04T17:26:35.070Z","6.2.0-openapi-15":"2018-12-07T09:58:48.345Z","6.2.0-openapi-16":"2018-12-07T10:31:30.520Z","7.0.0":"2018-12-07T11:50:43.998Z","7.0.1-0":"2018-12-07T17:46:24.941Z","7.0.1":"2018-12-10T06:23:48.412Z","7.1.0":"2018-12-12T13:37:57.406Z","7.1.1":"2019-02-02T15:20:42.948Z","7.2.0-5feeea4":"2019-03-15T09:11:24.854Z","7.2.0":"2019-03-25T15:19:07.055Z","7.2.1":"2019-03-27T09:40:13.036Z","7.2.2":"2019-03-29T12:08:30.949Z","7.2.3":"2019-04-01T13:12:52.263Z","7.2.4":"2019-04-16T10:12:53.938Z","7.3.0":"2019-04-23T10:16:44.192Z","7.4.0":"2019-04-23T13:33:24.416Z","7.5.0":"2019-04-23T13:51:42.168Z","7.3.1":"2019-04-23T14:03:39.071Z","7.6.0":"2019-04-23T15:03:24.320Z","7.6.1":"2019-05-08T13:55:12.643Z","7.6.2":"2019-05-16T09:44:06.354Z","7.6.1-15-ged78ff2":"2019-05-17T14:50:10.790Z","7.6.1-18-gb3cc099":"2019-05-21T08:26:01.720Z","7.6.1-23-g168e6e2":"2019-06-12T13:48:09.000Z","7.6.1-25-gc689d0e":"2019-06-12T15:33:37.096Z","7.6.3":"2019-06-21T13:22:04.057Z","7.6.4":"2019-07-03T14:35:43.755Z","8.0.0":"2019-07-05T12:18:21.257Z","8.1.0":"2019-07-29T15:09:27.372Z","8.1.1":"2019-07-30T09:00:31.387Z","8.1.2":"2019-07-30T09:44:11.261Z","8.1.3":"2019-07-31T16:26:59.278Z","8.1.4":"2019-09-10T11:48:05.481Z","9.0.0":"2019-09-13T14:53:55.100Z","9.0.1":"2019-09-18T14:17:14.459Z","9.0.1-cache.1":"2019-09-19T11:40:09.965Z","9.0.1-cache.2":"2019-09-19T11:53:30.074Z","9.0.1-cache.3":"2019-09-19T13:03:49.592Z","9.1.0":"2019-10-21T09:02:02.946Z","9.2.0":"2019-10-24T04:24:10.144Z","9.2.0-gb9a3f52":"2019-11-14T14:00:52.669Z","9.3.0":"2019-11-22T12:15:38.151Z","9.4.0":"2019-11-25T12:30:27.530Z","9.4.1":"2019-12-11T07:21:43.117Z","9.4.2":"2019-12-11T07:33:51.396Z","9.5.0":"2019-12-13T17:08:37.584Z","9.6.0":"2019-12-16T10:11:55.806Z","9.6.1":"2019-12-23T08:17:16.125Z","9.6.2":"2020-01-09T16:13:59.426Z","9.7.0":"2020-01-09T16:49:57.021Z","9.7.1":"2020-01-13T12:19:22.018Z","9.7.1-3-gc0047cb":"2020-01-14T09:12:09.645Z","9.7.1-6-g0969004":"2020-01-14T10:16:19.331Z","9.7.1-7-g2609a65":"2020-01-14T14:08:17.621Z","9.7.1-8-g1e2e40f":"2020-01-14T14:20:20.431Z","9.8.0":"2020-01-14T16:02:34.138Z","9.9.0":"2020-01-22T08:16:27.023Z","9.9.1":"2020-01-22T11:05:39.159Z","9.9.1-custom-generator-preview":"2020-01-23T09:18:55.832Z","9.9.1-custom-generator-preview-2":"2020-01-24T10:35:35.832Z","9.9.1-custom-generator-preview-3":"2020-01-24T10:41:02.737Z","9.10.0":"2020-01-28T14:42:22.898Z","9.10.0-1-g61d0088":"2020-02-03T16:26:29.255Z","9.10.0-1-geb2096f":"2020-02-03T16:30:33.408Z","9.10.1":"2020-02-03T16:33:34.685Z","9.11.0":"2020-02-04T11:13:04.890Z","9.11.1":"2020-02-11T08:46:51.162Z","9.11.1-without-cli":"2020-02-17T12:11:37.128Z","9.12.0":"2020-03-09T08:03:45.451Z","9.12.0-without-cli":"2020-03-09T08:04:01.681Z","9.12.1":"2020-03-12T11:49:42.705Z","9.12.1-without-cli":"2020-03-12T11:49:57.680Z","10.0.0-without-cli":"2020-03-22T08:57:47.937Z","10.0.0":"2020-03-22T08:57:59.585Z","10.0.1-without-cli":"2020-03-23T17:44:54.379Z","10.0.1":"2020-03-23T17:45:10.813Z","11.0.0-without-cli":"2020-03-27T13:22:56.329Z","11.0.0":"2020-03-27T13:23:12.891Z","11.1.0":"2020-04-12T12:34:18.007Z","11.1.0-without-cli":"2020-04-12T12:34:59.015Z","11.2.0":"2020-04-12T12:58:05.481Z","11.2.0-without-cli":"2020-04-12T12:58:16.124Z","12.0.0":"2020-05-04T11:24:40.158Z","12.0.0-without-cli":"2020-05-04T11:24:55.683Z","13.0.0":"2020-06-05T13:12:55.841Z","13.0.0-without-cli":"2020-06-05T13:13:28.065Z","14.0.0":"2020-06-15T10:00:38.607Z","14.0.0-without-cli":"2020-06-15T10:01:09.671Z","14.0.0-1-gf2ad69e":"2020-06-19T15:40:49.084Z","14.0.0-3-g82370ec":"2020-06-19T18:15:10.308Z","14.0.1":"2020-06-24T13:23:07.441Z","14.0.1-without-cli":"2020-06-24T13:23:28.757Z","14.0.2":"2020-06-24T13:52:33.269Z","14.0.2-without-cli":"2020-06-24T13:53:14.839Z","14.1.0":"2020-07-09T15:26:54.604Z","14.1.1":"2020-07-09T15:35:45.222Z","14.1.1-without-cli":"2020-07-09T15:36:07.648Z","14.2.0":"2020-07-10T09:22:28.176Z","14.2.0-without-cli":"2020-07-10T09:29:48.824Z","14.2.1":"2020-07-10T11:53:56.584Z","14.2.1-without-cli":"2020-07-10T11:54:13.045Z","14.3.0-without-cli":"2020-07-20T13:18:14.937Z","14.3.0":"2020-07-20T13:18:32.731Z","14.4.0":"2020-08-11T11:12:12.790Z","14.4.0-without-cli":"2020-08-11T11:12:28.904Z","14.5.0-without-cli":"2020-09-01T09:37:40.902Z","14.5.0":"2020-09-01T09:38:03.725Z","14.5.1":"2020-09-01T09:42:56.543Z","14.5.1-without-cli":"2020-09-01T09:43:03.439Z","15.0.0-alpha":"2020-09-29T15:46:56.342Z","15.0.0":"2020-10-07T13:28:34.748Z","15.0.0-without-cli":"2020-10-07T13:28:40.489Z","15.1.0":"2020-10-12T07:34:11.125Z","15.1.0-without-cli":"2020-10-12T07:34:16.463Z","15.1.1":"2020-10-14T13:35:47.738Z","15.1.1-without-cli":"2020-10-14T13:35:54.527Z","15.1.2":"2020-11-06T12:42:01.141Z","15.1.2-without-cli":"2020-11-06T12:42:12.563Z","15.1.3":"2020-12-11T10:40:35.882Z","15.1.3-without-cli":"2020-12-11T10:40:45.532Z","15.1.4-without-cli":"2021-01-04T09:27:48.028Z","15.2.0":"2021-02-01T16:45:22.045Z","15.2.0-without-cli":"2021-02-01T16:45:26.807Z","15.3.0":"2021-03-22T16:28:14.318Z","15.3.0-without-cli":"2021-03-22T16:28:19.978Z","15.4.0":"2021-03-31T13:11:09.418Z","15.4.1-g1d6980d":"2021-03-31T13:56:42.392Z","15.4.1-without-cli":"2021-03-31T17:07:46.801Z","15.4.1":"2021-03-31T17:07:57.025Z","15.4.2-without-cli":"2021-04-16T16:45:34.329Z","15.4.2":"2021-04-16T16:45:44.278Z","15.5.0-without-cli":"2021-04-22T07:29:45.262Z","15.5.0":"2021-04-22T07:30:02.618Z","15.5.1":"2021-04-22T07:35:15.361Z","15.5.1-without-cli":"2021-04-22T07:35:22.754Z","15.6.0-without-cli":"2021-05-05T07:46:42.525Z","15.6.0":"2021-05-05T07:46:57.533Z","15.7.0":"2021-07-13T11:59:23.089Z","15.7.0-without-cli":"2021-07-13T11:59:45.916Z","15.8.0-without-cli":"2021-07-20T14:21:58.330Z","15.8.0":"2021-07-20T14:22:15.442Z","15.9.0-without-cli":"2021-08-16T11:27:41.864Z","15.9.0":"2021-08-16T11:28:10.975Z","15.9.2":"2021-09-23T23:41:21.954Z","15.9.2-without-cli":"2021-09-24T13:04:40.131Z","15.9.3":"2021-12-03T09:51:45.137Z","15.9.3-without-cli":"2021-12-03T09:51:49.796Z","15.9.4":"2021-12-27T22:28:09.722Z","15.9.4-without-cli":"2021-12-27T22:28:16.394Z"},"maintainers":[{"name":"fabien0102","email":"fabien0102@gmail.com"},{"name":"stereobooster","email":"stereobooster@gmail.com"},{"name":"tejaskumar","email":"tejas@tejas.qa"},{"name":"mpotomin","email":"mikhail.potyomin@gmail.com"}],"description":"A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs","homepage":"https://github.com/contiamo/restful-react","keywords":["rest","restful","react","react-component","fetch","data fetching"],"repository":{"type":"git","url":"git+https://github.com/contiamo/restful-react.git"},"contributors":[{"name":"Tejas Kumar","email":"tejas@tejas.qa","url":"https://twitter.com/tejaskumar_"},{"name":"Fabien Bernard","email":"fabien@contiamo.com","url":"https://fabien0102.com/en"}],"bugs":{"url":"https://github.com/contiamo/restful-react/issues"},"license":"MIT","readme":"","readmeFilename":""}