├── .babelrc ├── .npmrc ├── .eslintrc.json ├── __tests__ ├── .eslintrc.json ├── actions │ ├── clear.spec.js │ ├── asyncSideEffects.spec.js │ ├── query.spec.js │ ├── executeFetch.spec.js │ └── crud.spec.js ├── config.spec.js ├── index.spec.js ├── helpers │ ├── url.spec.js │ └── hash.spec.js ├── selectors.spec.js └── reducer.spec.js ├── .github ├── labeler.yml ├── workflows │ ├── pr-labeler.yml │ ├── stale.yml │ ├── health-check.yml │ ├── tests.yml │ └── release.yml ├── ISSUE_TEMPLATE │ ├── feature-request.md │ └── bug-report.md └── pull_request_template.md ├── iguazu-rest.png ├── CODEOWNERS ├── .gitignore ├── .npmignore ├── src ├── actions │ ├── clear.js │ ├── query.js │ ├── asyncSideEffects.js │ ├── executeFetch.js │ └── crud.js ├── config.js ├── errors.js ├── index.js ├── helpers │ ├── hash.js │ └── url.js ├── types.js ├── selectors.js └── reducer.js ├── setupJest.js ├── commitlint.config.js ├── SECURITY.md ├── CHANGELOG.md ├── package.json ├── CONTRIBUTING.md ├── CODE_OF_CONDUCT.md ├── LICENSE.txt └── README.md /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["amex"] 3 | } 4 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | registry=https://registry.npmjs.org 2 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "amex" 3 | } 4 | -------------------------------------------------------------------------------- /__tests__/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "amex/test" 3 | } 4 | -------------------------------------------------------------------------------- /.github/labeler.yml: -------------------------------------------------------------------------------- 1 | one-app-team-review-requested: 2 | - '**/*' 3 | -------------------------------------------------------------------------------- /iguazu-rest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/americanexpress/iguazu-rest/HEAD/iguazu-rest.png -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | # https://help.github.com/en/articles/about-code-owners 2 | 3 | * @americanexpress/one-app-team @americanexpress/one-amex-admins 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # node & npm 2 | node_modules 3 | *.log 4 | 5 | # test 6 | test-results 7 | .jest-cache 8 | 9 | # build 10 | lib 11 | /*.tgz 12 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | test-results 2 | src/* 3 | __tests__ 4 | *.md 5 | CODEOWNERS 6 | .travis.yml 7 | .babelrc 8 | .eslintrc.json 9 | *.tgz 10 | test-setup.js 11 | .jest-cache -------------------------------------------------------------------------------- /.github/workflows/pr-labeler.yml: -------------------------------------------------------------------------------- 1 | name: "Pull Request Labeler" 2 | on: 3 | pull_request_target: 4 | types: [opened, reopened] 5 | 6 | jobs: 7 | triage: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/labeler@v3 11 | with: 12 | repo-token: "${{ secrets.GITHUB_TOKEN }}" 13 | -------------------------------------------------------------------------------- /src/actions/clear.js: -------------------------------------------------------------------------------- 1 | import { CLEAR_COLLECTION, CLEAR_RESOURCE } from '../types'; 2 | 3 | export function clearResource({ resource, id }) { 4 | return { resource, id, type: CLEAR_RESOURCE }; 5 | } 6 | 7 | export function clearCollection({ resource, id, opts }) { 8 | return { 9 | resource, id, opts, type: CLEAR_COLLECTION, 10 | }; 11 | } 12 | -------------------------------------------------------------------------------- /__tests__/actions/clear.spec.js: -------------------------------------------------------------------------------- 1 | import { CLEAR_COLLECTION, CLEAR_RESOURCE } from '../../src/types'; 2 | import { clearCollection, clearResource } from '../../src'; 3 | 4 | describe('clearing', () => { 5 | it('resource', () => { 6 | expect(clearResource({ resource: 'users', id: 234 })) 7 | .toEqual({ type: CLEAR_RESOURCE, id: 234, resource: 'users' }); 8 | }); 9 | 10 | it('collection', () => { 11 | expect(clearCollection({ resource: 'users', opts: { query: 'some&query' } })) 12 | .toEqual({ type: CLEAR_COLLECTION, resource: 'users', opts: { query: 'some&query' } }); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: Mark stale issues and pull requests 2 | 3 | on: 4 | schedule: 5 | - cron: "0 0 * * *" 6 | 7 | jobs: 8 | stale: 9 | 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/stale@v3 14 | with: 15 | repo-token: ${{ secrets.GITHUB_TOKEN }} 16 | stale-issue-message: 'This issue is stale because it has been open 30 days with no activity.' 17 | stale-pr-message: 'This pull request is stale because it has been open 30 days with no activity.' 18 | stale-issue-label: 'stale-issue' 19 | exempt-issue-labels: 'enhancement,documentation,good-first-issue,question' 20 | stale-pr-label: 'stale-pr' 21 | exempt-pr-labels: 'work-in-progress' 22 | days-before-stale: 30 23 | days-before-close: -1 24 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature-request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Create a feature request for iguazu-rest 4 | --- 5 | 6 | # 💡 Feature request 7 | 8 | ## Is your feature request related to a problem? Please describe 9 | 10 | A clear and concise description of what you want and what your use case is. 11 | 12 | ## Example 13 | 14 | Please include a basic code example of the new feature. Skip this section if not applicable. 15 | 16 | ## Describe the solution you'd like 17 | 18 | A clear and concise description of what you want to happen. 19 | 20 | ## Describe alternatives you've considered 21 | 22 | A clear and concise description of any alternative solutions or features you've considered. 23 | 24 | ## Additional context 25 | 26 | Add any other context or screenshots about the feature request here.💡 27 | -------------------------------------------------------------------------------- /.github/workflows/health-check.yml: -------------------------------------------------------------------------------- 1 | name: Health Check 2 | 3 | on: 4 | schedule: 5 | # At minute 0 past hour 0800 and 2000. 6 | - cron: '0 8,20 * * *' 7 | 8 | jobs: 9 | tests: 10 | runs-on: ubuntu-latest 11 | strategy: 12 | matrix: 13 | node: [ '10.x', '12.x', '14.x' ] 14 | name: Node ${{ matrix.node }} 15 | steps: 16 | - uses: actions/checkout@v2 17 | - run: | 18 | git remote set-branches --add origin main 19 | git fetch 20 | - name: Setup Node 21 | uses: actions/setup-node@v1 22 | with: 23 | node-version: ${{ matrix.node }} 24 | - name: Install Dependencies 25 | run: npm ci 26 | env: 27 | NODE_ENV: development 28 | - name: Run Test Script 29 | run: npm run test 30 | env: 31 | NODE_ENV: production 32 | -------------------------------------------------------------------------------- /setupJest.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | /* eslint import/no-extraneous-dependencies: ["error", { "devDependencies": true }] */ 18 | 19 | require('@babel/polyfill'); 20 | global.fetch = require('jest-fetch-mock'); 21 | -------------------------------------------------------------------------------- /commitlint.config.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express 11 | * or implied. See the License for the specific language governing permissions and limitations 12 | * under the License. 13 | */ 14 | 15 | module.exports = { 16 | extends: ['@commitlint/config-conventional'], 17 | rules: { 18 | 'scope-case': [2, 'always', ['pascal-case', 'camel-case', 'kebab-case']], 19 | }, 20 | }; 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a bug report for iguazu-rest 4 | --- 5 | 6 | # 🐞 Bug Report 7 | 8 | ## Describe the bug 9 | 10 | A clear and concise description of what the bug is. 11 | 12 | ## To Reproduce 13 | 14 | Steps to reproduce the behavior, please provide code snippets or a repository: 15 | 16 | 1. Go to '...' 17 | 2. Click on '....' 18 | 3. Scroll down to '....' 19 | 4. See error 20 | 21 | ## Expected behavior 22 | 23 | A clear and concise description of what you expected to happen. 24 | 25 | ## Screenshots 26 | 27 | If applicable, add screenshots to help explain your problem. 28 | 29 | ## System information 30 | 31 | - OS: [e.g. macOS, Windows] 32 | - Browser (if applies) [e.g. chrome, safari] 33 | - Version of iguazu-rest: [e.g. 5.0.0] 34 | - Node version:[e.g 10.15.1] 35 | 36 | ## Additional context 37 | 38 | Add any other context about the problem here. -------------------------------------------------------------------------------- /src/config.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | const config = { 18 | baseFetch: fetch, 19 | composeFetch: (fetch) => fetch, 20 | getToState: (state) => state.resources, 21 | }; 22 | 23 | export function configureIguazuREST(customConfig) { 24 | Object.assign(config, customConfig); 25 | } 26 | 27 | export default config; 28 | -------------------------------------------------------------------------------- /src/errors.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | export const ID_TYPE_ERROR = 'Collection response must be an array of objects containing a unique id key (either "id" by default, or a custom "idKey" of your choice). The ID must be an object, number, or string. For non-compliant API responses, you can transform the data using a custom "transformData" function.'; 18 | export const ARRAY_RESPONSE_ERROR = 'Resource call must return an object, not an array'; 19 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | tests: 10 | runs-on: ubuntu-latest 11 | strategy: 12 | matrix: 13 | node: [ '16.x', '18.x'] 14 | name: Node ${{ matrix.node }} 15 | steps: 16 | - uses: actions/checkout@v2 17 | - run: | 18 | git remote set-branches --add origin main 19 | git fetch 20 | - name: Setup Node 21 | uses: actions/setup-node@v1 22 | with: 23 | node-version: ${{ matrix.node }} 24 | - name: Install Dependencies 25 | run: npm ci 26 | env: 27 | NODE_ENV: development 28 | - name: Unit Tests 29 | run: npm run test:unit 30 | env: 31 | NODE_ENV: production 32 | - name: Git History Test 33 | run: npm run test:git-history 34 | env: 35 | NODE_ENV: production 36 | - name: Lockfile Lint Test 37 | run: npm run test:lockfile 38 | env: 39 | NODE_ENV: production 40 | - name: Lint 41 | run: npm run test:lint 42 | env: 43 | NODE_ENV: production 44 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | prepare: 10 | runs-on: ubuntu-latest 11 | if: "! contains(github.event.head_commit.message, '[skip ci]')" 12 | steps: 13 | - run: echo "${{ github.event.head_commit.message }}" 14 | release: 15 | needs: prepare 16 | name: Release 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Checkout 20 | uses: actions/checkout@v2 21 | with: 22 | persist-credentials: false 23 | - name: Setup Node.js 24 | uses: actions/setup-node@v1 25 | with: 26 | node-version: 18 27 | - name: Install dependencies 28 | run: npm ci 29 | - name: Release 30 | env: 31 | GIT_AUTHOR_EMAIL: ${{ secrets.GIT_AUTHOR_EMAIL }} 32 | GIT_AUTHOR_NAME: ${{ secrets.GIT_AUTHOR_NAME }} 33 | GIT_COMMITTER_EMAIL: ${{ secrets.GIT_COMMITTER_EMAIL }} 34 | GIT_COMMITTER_NAME: ${{ secrets.GIT_COMMITTER_NAME }} 35 | GITHUB_TOKEN: ${{ secrets.PA_TOKEN }} 36 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 37 | run: npx semantic-release 38 | -------------------------------------------------------------------------------- /__tests__/config.spec.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import config, { 18 | configureIguazuREST, 19 | } from '../src/config'; 20 | 21 | describe('config', () => { 22 | describe('default config', () => { 23 | it('should be initialized with some defaults', () => { 24 | expect(config.baseFetch).toBe(fetch); 25 | const state = { resources: 'resources state' }; 26 | expect(config.getToState(state)).toBe('resources state'); 27 | }); 28 | }); 29 | 30 | describe('configureIguazuREST', () => { 31 | it('should allow you to add to the config', () => { 32 | configureIguazuREST({ someKey: 'someValue' }); 33 | expect(config.someKey).toBe('someValue'); 34 | }); 35 | }); 36 | }); 37 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | ## American Express Responsible Disclosure Policy 2 | 3 | At American Express, we take cybersecurity seriously and value the contributions of the security 4 | community at large. The responsible disclosure of potential issues helps us ensure the security and 5 | privacy of our customers and data. If you believe you’ve found a security issue in one of our 6 | products or services please send it to us and include the following details with your report: 7 | - A description of the issue and where it is located. 8 | - A description of the steps required to reproduce the issue. 9 | 10 | Please note that this should not be construed as encouragement or permission to perform any of the 11 | following activities: 12 | - Hack, penetrate, or otherwise attempt to gain unauthorized access to American Express 13 | applications, systems, or data in violation of applicable law; 14 | - Download, copy, disclose or use any proprietary or confidential American Express data, including 15 | customer data; and 16 | - Adversely impact American Express or the operation of American Express applications or systems. 17 | 18 | American Express does not waive any rights or claims with respect to such activities. 19 | 20 | Please email your message and any attachments to 21 | [responsible.disclosure@aexp.com](mailto:responsible.disclosure@aexp.com) 22 | 23 | #### Thank you for helping us keep American Express customers and data safe. -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import { 18 | loadResource, 19 | loadCollection, 20 | createResource, 21 | updateResource, 22 | updateCollection, 23 | destroyResource, 24 | patchResource, 25 | } from './actions/crud'; 26 | 27 | import { 28 | queryResource, 29 | queryCollection, 30 | } from './actions/query'; 31 | 32 | import { 33 | getResource, 34 | getResourceIsLoaded, 35 | getCollection, 36 | getCollectionIsLoaded, 37 | } from './selectors'; 38 | 39 | import { 40 | clearResource, 41 | clearCollection, 42 | } from './actions/clear'; 43 | 44 | import resourcesReducer from './reducer'; 45 | 46 | import { configureIguazuREST } from './config'; 47 | 48 | /* Public API */ 49 | export { 50 | loadResource, 51 | loadCollection, 52 | createResource, 53 | updateResource, 54 | updateCollection, 55 | patchResource, 56 | destroyResource, 57 | queryResource, 58 | queryCollection, 59 | getResource, 60 | getResourceIsLoaded, 61 | getCollection, 62 | getCollectionIsLoaded, 63 | clearResource, 64 | clearCollection, 65 | resourcesReducer, 66 | configureIguazuREST, 67 | }; 68 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Description 4 | 5 | 6 | ## Motivation and Context 7 | 8 | 9 | 10 | ## How Has This Been Tested? 11 | 12 | 13 | 14 | 15 | ## Types of Changes 16 | 17 | - [ ] Bug fix (non-breaking change which fixes an issue) 18 | - [ ] New feature (non-breaking change which adds functionality) 19 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) 20 | - [ ] Documentation (adding or updating documentation) 21 | - [ ] Dependency update 22 | 23 | ## Checklist: 24 | 25 | 26 | - [ ] My change requires a change to the documentation and I have updated the documentation accordingly. 27 | - [ ] My changes are in sync with the code style of this project. 28 | - [ ] There aren't any other open Pull Requests for the same issue/update. 29 | - [ ] These changes should be applied to a maintenance branch. 30 | - [ ] I have added the Apache 2.0 license header to any new files created. 31 | 32 | ## What is the Impact to Developers Using Iguazu-Rest? 33 | 34 | -------------------------------------------------------------------------------- /__tests__/index.spec.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import { 18 | loadResource, 19 | loadCollection, 20 | createResource, 21 | updateResource, 22 | updateCollection, 23 | destroyResource, 24 | queryResource, 25 | queryCollection, 26 | getResource, 27 | getCollection, 28 | clearResource, 29 | clearCollection, 30 | resourcesReducer, 31 | configureIguazuREST, 32 | } from '../src'; 33 | 34 | describe('index', () => { 35 | it('should expose the expected publicAPI', () => { 36 | expect(loadResource).toBeDefined(); 37 | expect(loadCollection).toBeDefined(); 38 | expect(createResource).toBeDefined(); 39 | expect(updateResource).toBeDefined(); 40 | expect(destroyResource).toBeDefined(); 41 | expect(queryResource).toBeDefined(); 42 | expect(queryCollection).toBeDefined(); 43 | expect(getResource).toBeDefined(); 44 | expect(getCollection).toBeDefined(); 45 | expect(clearResource).toBeDefined(); 46 | expect(clearCollection).toBeDefined(); 47 | expect(updateCollection).toBeDefined(); 48 | 49 | expect(resourcesReducer).toBeDefined(); 50 | expect(configureIguazuREST).toBeDefined(); 51 | }); 52 | }); 53 | -------------------------------------------------------------------------------- /src/helpers/hash.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import hash from 'object-hash'; 18 | import { Map as iMap } from 'immutable'; 19 | import { ID_TYPE_ERROR } from '../errors'; 20 | 21 | function hashWithoutPrototypes(obj) { 22 | return hash(obj, { respectType: false }); 23 | } 24 | 25 | export function valuesAsStrings(obj) { 26 | return iMap(obj).map((v) => v.toString()).toJS(); 27 | } 28 | 29 | function getIdAsObject(id) { 30 | const idType = typeof id; 31 | if (idType === 'object' && id !== null) { 32 | return id; 33 | } 34 | if (idType === 'string' || idType === 'number') { 35 | return { id }; 36 | } 37 | throw new Error(ID_TYPE_ERROR); 38 | } 39 | 40 | export function convertId(originalId) { 41 | return valuesAsStrings(getIdAsObject(originalId)); 42 | } 43 | 44 | export function getResourceIdHash(originalId) { 45 | const idObj = convertId(originalId); 46 | return hashWithoutPrototypes(idObj); 47 | } 48 | 49 | export function getCollectionIdHash(id) { 50 | if (id) { 51 | const idObj = convertId(id); 52 | delete idObj.id; 53 | return hashWithoutPrototypes(idObj); 54 | } 55 | 56 | return hashWithoutPrototypes({}); 57 | } 58 | 59 | export function getQueryHash(opts = {}) { 60 | return hashWithoutPrototypes(opts.query || {}); 61 | } 62 | -------------------------------------------------------------------------------- /src/actions/query.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import { 18 | getResource, 19 | getCollection, 20 | getResourceIsLoaded, 21 | getCollectionIsLoaded, 22 | } from '../selectors'; 23 | import { 24 | loadResource, 25 | loadCollection, 26 | } from './crud'; 27 | import { 28 | handleQueryPromiseRejection, 29 | } from './asyncSideEffects'; 30 | 31 | export function queryResource({ 32 | resource, id, opts, forceFetch, 33 | }) { 34 | return (dispatch, getState) => { 35 | const state = getState(); 36 | const data = getResource({ resource, id, opts })(state); 37 | const status = getResourceIsLoaded({ resource, id, opts })(state) && !forceFetch ? 'complete' : 'loading'; 38 | const error = data instanceof Error && data; 39 | const promise = dispatch(loadResource({ 40 | resource, id, opts, forceFetch, 41 | })); 42 | handleQueryPromiseRejection(promise); 43 | 44 | return { 45 | data, status, error, promise, 46 | }; 47 | }; 48 | } 49 | 50 | export function queryCollection({ 51 | resource, id, opts, forceFetch, 52 | }) { 53 | return (dispatch, getState) => { 54 | const state = getState(); 55 | const data = getCollection({ resource, id, opts })(state); 56 | const status = getCollectionIsLoaded({ resource, id, opts })(state) && !forceFetch ? 'complete' : 'loading'; 57 | const error = data instanceof Error && data; 58 | const promise = dispatch(loadCollection({ 59 | resource, id, opts, forceFetch, 60 | })); 61 | handleQueryPromiseRejection(promise); 62 | 63 | return { 64 | data, status, error, promise, 65 | }; 66 | }; 67 | } 68 | -------------------------------------------------------------------------------- /__tests__/actions/asyncSideEffects.spec.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import { 18 | handleQueryPromiseRejection, 19 | waitAndDispatchFinished, 20 | } from '../../src/actions/asyncSideEffects'; 21 | 22 | import * as types from '../../src/types'; 23 | 24 | describe('async side effectsQuery', () => { 25 | describe('handleQueryPromiseRejection', () => { 26 | it('should catch the passed promise', async () => { 27 | expect.assertions(1); 28 | await expect(handleQueryPromiseRejection(Promise.reject())).resolves.toBeUndefined(); 29 | }); 30 | }); 31 | 32 | describe('waitAndDispatchFinished', () => { 33 | const dispatch = jest.fn(); 34 | 35 | it('should dispatch the passed action along with data that was successfully loaded', async () => { 36 | expect.assertions(1); 37 | const action = { type: 'LOAD_RESOURCE' }; 38 | const promise = Promise.resolve('async data'); 39 | const thunk = waitAndDispatchFinished(promise, action); 40 | await thunk(dispatch); 41 | expect(dispatch).toHaveBeenCalledWith({ type: types.LOAD_RESOURCE_FINISHED, data: 'async data' }); 42 | }); 43 | 44 | it('should dispatch the passed action along with the error when the load failed', async () => { 45 | expect.assertions(1); 46 | const action = { type: 'LOAD_RESOURCE' }; 47 | const error = new Error('async error'); 48 | const promise = Promise.reject(error); 49 | const thunk = waitAndDispatchFinished(promise, action); 50 | await thunk(dispatch); 51 | expect(dispatch).toHaveBeenCalledWith({ type: types.LOAD_RESOURCE_ERROR, data: error }); 52 | }); 53 | }); 54 | }); 55 | -------------------------------------------------------------------------------- /src/types.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | export const LOAD_STARTED = '@@iguazu-rest/LOAD_STARTED'; 18 | export const LOAD_COLLECTION_STARTED = '@@iguazu-rest/LOAD_COLLECTION_STARTED'; 19 | export const CREATE_STARTED = '@@iguazu-rest/CREATE_STARTED'; 20 | export const UPDATE_STARTED = '@@iguazu-rest/UPDATE_STARTED'; 21 | export const UPDATE_COLLECTION_STARTED = '@@iguazu-rest/UPDATE_COLLECTION_STARTED'; 22 | export const PATCH_STARTED = '@@iguazu-rest/PATCH_STARTED'; 23 | export const DESTROY_STARTED = '@@iguazu-rest/DESTROY_STARTED'; 24 | export const LOAD_FINISHED = '@@iguazu-rest/LOAD_FINISHED'; 25 | export const LOAD_ERROR = '@@iguazu-rest/LOAD_ERROR'; 26 | export const LOAD_COLLECTION_FINISHED = '@@iguazu-rest/LOAD_COLLECTION_FINISHED'; 27 | export const LOAD_COLLECTION_ERROR = '@@iguazu-rest/LOAD_COLLECTION_ERROR'; 28 | export const CREATE_FINISHED = '@@iguazu-rest/CREATE_FINISHED'; 29 | export const CREATE_ERROR = '@@iguazu-rest/CREATE_ERROR'; 30 | export const UPDATE_FINISHED = '@@iguazu-rest/UPDATE_FINISHED'; 31 | export const UPDATE_COLLECTION_FINISHED = '@@iguazu-rest/UPDATE_COLLECTION_FINISHED'; 32 | export const UPDATE_COLLECTION_ERROR = '@@iguazu-rest/UPDATE_COLLECTION_ERROR'; 33 | export const PATCH_FINISHED = '@@iguazu-rest/PATCH_FINISHED'; 34 | export const UPDATE_ERROR = '@@iguazu-rest/UPDATE_ERROR'; 35 | export const PATCH_ERROR = '@@iguazu-rest/PATCH_ERROR'; 36 | export const DESTROY_FINISHED = '@@iguazu-rest/DESTROY_FINISHED'; 37 | export const DESTROY_ERROR = '@@iguazu-rest/DESTROY_ERROR'; 38 | export const RESET = '@@iguazu-rest/RESET'; 39 | export const CLEAR_RESOURCE = '@@iguazu-rest/CLEAR_RESOURCE'; 40 | export const CLEAR_COLLECTION = '@@iguazu-rest/CLEAR_COLLECTION'; 41 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [1.11.1](https://github.com/americanexpress/iguazu-rest/compare/v1.11.0...v1.11.1) (2023-08-22) 2 | 3 | 4 | ### Bug Fixes 5 | 6 | * **deps:** security update ([#52](https://github.com/americanexpress/iguazu-rest/issues/52)) ([d972463](https://github.com/americanexpress/iguazu-rest/commit/d972463ce25c791e1474bf14b68702530b002541)) 7 | 8 | # [1.11.0](https://github.com/americanexpress/iguazu-rest/compare/v1.10.2...v1.11.0) (2022-08-18) 9 | 10 | 11 | ### Features 12 | 13 | * **selector:** rename and expose loaded selectors ([#43](https://github.com/americanexpress/iguazu-rest/issues/43)) ([3f6cfba](https://github.com/americanexpress/iguazu-rest/commit/3f6cfbafecb226928c306a195a2aa6a17c855c59)) 14 | 15 | ## [1.10.2](https://github.com/americanexpress/iguazu-rest/compare/v1.10.1...v1.10.2) (2022-02-25) 16 | 17 | 18 | ### Bug Fixes 19 | 20 | * **labeler:** outdated label usage ([#39](https://github.com/americanexpress/iguazu-rest/issues/39)) ([a313cea](https://github.com/americanexpress/iguazu-rest/commit/a313cea777ef78fa40e44a57203011f5d84c925e)) 21 | 22 | ## [1.10.1](https://github.com/americanexpress/iguazu-rest/compare/v1.10.0...v1.10.1) (2020-10-22) 23 | 24 | 25 | ### Bug Fixes 26 | 27 | * **executeFetch:** revert forced methods ([#22](https://github.com/americanexpress/iguazu-rest/issues/22)) ([d4206b7](https://github.com/americanexpress/iguazu-rest/commit/d4206b7cbd1c2f64d93fd7be9d5f984b10338693)) 28 | 29 | # [1.10.0](https://github.com/americanexpress/iguazu-rest/compare/v1.9.1...v1.10.0) (2020-09-08) 30 | 31 | 32 | ### Features 33 | 34 | * **updateCollection:** added ([573ef1c](https://github.com/americanexpress/iguazu-rest/commit/573ef1c484d93946d9f7cc5695a6634daafd050a)) 35 | 36 | ## [1.9.1](https://github.com/americanexpress/iguazu-rest/compare/v1.9.0...v1.9.1) (2020-04-28) 37 | 38 | 39 | ### Bug Fixes 40 | 41 | * **errors:** clarify messaging for collection fetch errors ([e8627cf](https://github.com/americanexpress/iguazu-rest/commit/e8627cf60eeaea6fdaab1217dab20f29dd012fbb)) 42 | 43 | # [1.9.0](https://github.com/americanexpress/iguazu-rest/compare/v1.8.0...v1.9.0) (2020-04-28) 44 | 45 | 46 | ### Features 47 | 48 | * **buildFetchUrl:** enable optional ids via question mark ([82e1f54](https://github.com/americanexpress/iguazu-rest/commit/82e1f54cc96ef50d2aa883f7d35d9adc12d0dd10)) 49 | * **readme:** document how to use query params ([78da466](https://github.com/americanexpress/iguazu-rest/commit/78da466af8003da35cf900337e8d277f6e7c72d3)) 50 | 51 | # [1.8.0](https://github.com/americanexpress/iguazu-rest/compare/v1.7.0...v1.8.0) (2020-03-10) 52 | 53 | 54 | ### Features 55 | 56 | * **executeFetch:** utilize composeFetch function ([7f0608b](https://github.com/americanexpress/iguazu-rest/commit/7f0608b058dd67bb77a887e8a449e4359f983321)) 57 | -------------------------------------------------------------------------------- /src/actions/asyncSideEffects.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import * as types from '../types'; 18 | 19 | /** 20 | * Some actions which are asynchronous need to act on a promise, but also return the original 21 | * promise to achieve desired behavior. Moving these asynchronous side effects to their own 22 | * functions in a different file makes it easier to mock them and make sure they were called 23 | * with the correct inputs in one test script and test their behavior in another test script. 24 | */ 25 | 26 | /** 27 | * The promise in queryResource and queryCollection is exclusively used to wait on asynchronous 28 | * data before server-side rendering. The promise should reject if the load failed, so that iguazu 29 | * doesn't continue to load data that it does not need when it will just render an error state. On 30 | * the client, nothing waits on the promise via `.then` or `await`. Instead, a redux action is fired 31 | * when the async task is finished, which updates the store, which then triggers loadDataAsProps to 32 | * run. Whether the async task finished successfully or not will be made apparent by what is stored 33 | * in state. So it seems like the promise rejection is not being handled, but ultimately it is. This 34 | * is a simple catch to assure the browser that the promise has indeed been dealt with so it will 35 | * not emit a `unhandledrejection` event. 36 | */ 37 | export function handleQueryPromiseRejection(promise) { 38 | return promise.then(null, () => { /* Swallow */ }); 39 | } 40 | 41 | /** 42 | * The promise from executeFetch will be caught by the handleQueryPromiseRejection function above. 43 | * Its job is to catch if the network job failed, because nothing is broken if it did. It should 44 | * not catch any errors that happen as a result of the network call failing which is what happens 45 | * if the promise chain returned from executeFetch dispatches redux actions inside of it. The redux 46 | * actions can cause a rerender and a render error would be swallowed making it hard to debug what 47 | * went wrong. 48 | */ 49 | export function waitAndDispatchFinished(promise, action) { 50 | return async (dispatch) => { 51 | let data; 52 | try { 53 | data = await promise; 54 | dispatch({ ...action, type: types[`${action.type}_FINISHED`], data }); 55 | } catch (e) { 56 | data = e; 57 | dispatch({ ...action, type: types[`${action.type}_ERROR`], data }); 58 | } 59 | }; 60 | } 61 | -------------------------------------------------------------------------------- /src/selectors.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import { Map as iMap } from 'immutable'; 18 | 19 | import config from './config'; 20 | import { 21 | getResourceIdHash, 22 | getCollectionIdHash, 23 | getQueryHash, 24 | } from './helpers/hash'; 25 | 26 | export function getResourceIsLoaded({ resource, id }) { 27 | return (state) => { 28 | const resourceState = config.getToState(state).get(resource, iMap()); 29 | const idHash = getResourceIdHash(id); 30 | return !!resourceState.getIn(['items', idHash]) || !!resourceState.getIn(['error', idHash]); 31 | }; 32 | } 33 | 34 | export function getResource({ resource, id }) { 35 | return (state) => { 36 | const resourceState = config.getToState(state).get(resource, iMap()); 37 | const error = resourceState.getIn(['error', getResourceIdHash(id)]); 38 | if (error) return error; 39 | 40 | const item = resourceState.getIn(['items', getResourceIdHash(id)]); 41 | return iMap.isMap(item) ? item.toJS() : item; 42 | }; 43 | } 44 | 45 | export function resourceIsLoading({ resource, id }) { 46 | return (state) => !!config.getToState(state).getIn([resource, 'loading', getResourceIdHash(id)]); 47 | } 48 | 49 | export function getResourceLoadPromise({ resource, id }) { 50 | return (state) => config.getToState(state).getIn([resource, 'loading', getResourceIdHash(id)]); 51 | } 52 | 53 | export function getCollectionIsLoaded({ resource, id, opts }) { 54 | return (state) => { 55 | const idHash = getCollectionIdHash(id); 56 | const queryHash = getQueryHash(opts); 57 | return !!config.getToState(state).getIn([resource, 'collections', idHash, queryHash]); 58 | }; 59 | } 60 | 61 | export function getCollection({ resource, id, opts }) { 62 | return (state) => { 63 | const resourceState = config.getToState(state).get(resource, iMap()); 64 | const idHash = getCollectionIdHash(id); 65 | const queryHash = getQueryHash(opts); 66 | const error = resourceState.getIn(['collections', idHash, queryHash, 'error']); 67 | if (error) return error; 68 | 69 | const { associatedIds } = resourceState.getIn(['collections', idHash, queryHash], iMap({ associatedIds: [] })).toJS(); 70 | 71 | return associatedIds.map((resourceId) => resourceState.getIn(['items', resourceId]).toJS()); 72 | }; 73 | } 74 | 75 | export function collectionIsLoading({ resource, id, opts }) { 76 | return (state) => !!config.getToState(state).getIn([resource, 'loading', getCollectionIdHash(id), getQueryHash(opts)]); 77 | } 78 | 79 | export function getCollectionLoadPromise({ resource, id, opts }) { 80 | return (state) => config.getToState(state).getIn([resource, 'loading', getCollectionIdHash(id), getQueryHash(opts)]); 81 | } 82 | -------------------------------------------------------------------------------- /src/actions/executeFetch.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import merge from 'deepmerge'; 18 | 19 | import * as types from '../types'; 20 | import { buildFetchUrl } from '../helpers/url'; 21 | import config from '../config'; 22 | import { waitAndDispatchFinished } from './asyncSideEffects'; 23 | 24 | function startsWith(string, target) { 25 | return String(string).slice(0, target.length) === target; 26 | } 27 | 28 | async function extractDataFromResponse(res) { 29 | const contentType = res.headers.get('Content-Type'); 30 | const isJson = startsWith(contentType, 'application/json'); 31 | const body = await res[isJson ? 'json' : 'text'](); 32 | const { status } = res; 33 | 34 | return res.ok 35 | ? Promise.resolve(body) 36 | : Promise.reject(Object.assign(new Error(`${res.statusText} (${res.url})`), { body, status })); 37 | } 38 | 39 | const actionTypeMethodMap = { 40 | LOAD: 'GET', 41 | LOAD_COLLECTION: 'GET', 42 | CREATE: 'POST', 43 | UPDATE: 'PUT', 44 | UPDATE_COLLECTION: 'POST', 45 | DESTROY: 'DELETE', 46 | PATCH: 'PATCH', 47 | }; 48 | 49 | async function getAsyncData({ 50 | resource, id, opts, actionType, state, fetchClient, 51 | }) { 52 | const { 53 | resources, 54 | defaultOpts, 55 | baseFetch, 56 | composeFetch, 57 | } = config; 58 | const { url, opts: resourceOpts } = resources[resource].fetch(id, actionType, state); 59 | 60 | const fetchOpts = merge.all([ 61 | { method: actionTypeMethodMap[actionType] }, 62 | defaultOpts || {}, 63 | resourceOpts || {}, 64 | opts || {}, 65 | ]); 66 | const fetchUrl = buildFetchUrl({ url, id, opts: fetchOpts }); 67 | 68 | const selectedFetchClient = fetchClient || baseFetch; 69 | const composedFetchClient = composeFetch(selectedFetchClient); 70 | 71 | const res = await composedFetchClient(fetchUrl, fetchOpts); 72 | const rawData = await extractDataFromResponse(res); 73 | const { transformData } = config.resources[resource]; 74 | const data = transformData ? transformData(rawData, { id, opts, actionType }) : rawData; 75 | 76 | return data; 77 | } 78 | 79 | export default function executeFetch({ 80 | resource, id, opts, actionType, 81 | }) { 82 | return (dispatch, getState, { fetchClient } = {}) => { 83 | const promise = getAsyncData({ 84 | resource, 85 | id, 86 | opts, 87 | actionType, 88 | state: getState(), 89 | fetchClient, 90 | }); 91 | dispatch({ 92 | type: types[`${actionType}_STARTED`], resource, id, opts, promise, 93 | }); 94 | dispatch(waitAndDispatchFinished(promise, { 95 | type: actionType, resource, id, opts, 96 | })); 97 | 98 | return promise; 99 | }; 100 | } 101 | -------------------------------------------------------------------------------- /src/actions/crud.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import { 18 | getResourceIsLoaded, 19 | getResource, 20 | resourceIsLoading, 21 | getResourceLoadPromise, 22 | getCollectionIsLoaded, 23 | getCollection, 24 | collectionIsLoading, 25 | getCollectionLoadPromise, 26 | } from '../selectors'; 27 | import executeFetch from './executeFetch'; 28 | 29 | export function loadResource({ 30 | resource, id, opts, forceFetch, 31 | }) { 32 | return (dispatch, getState) => { 33 | const state = getState(); 34 | let promise; 35 | if (getResourceIsLoaded({ resource, id })(state) && !forceFetch) { 36 | const data = getResource({ resource, id })(state); 37 | promise = data instanceof Error ? Promise.reject(data) : Promise.resolve(data); 38 | } else if (resourceIsLoading({ resource, id })(state) && !forceFetch) { 39 | promise = getResourceLoadPromise({ resource, id })(state); 40 | } else { 41 | promise = dispatch(executeFetch({ 42 | resource, id, opts, actionType: 'LOAD', 43 | })); 44 | } 45 | 46 | return promise; 47 | }; 48 | } 49 | 50 | export function loadCollection({ 51 | resource, id, opts, forceFetch, 52 | }) { 53 | return (dispatch, getState) => { 54 | const state = getState(); 55 | let promise; 56 | if (getCollectionIsLoaded({ resource, id, opts })(state) && !forceFetch) { 57 | const data = getCollection({ resource, id, opts })(state); 58 | promise = data instanceof Error ? Promise.reject(data) : Promise.resolve(data); 59 | } else if (collectionIsLoading({ resource, id, opts })(state) && !forceFetch) { 60 | promise = getCollectionLoadPromise({ resource, id, opts })(state); 61 | } else { 62 | promise = dispatch(executeFetch({ 63 | resource, id, opts, actionType: 'LOAD_COLLECTION', 64 | })); 65 | } 66 | 67 | return promise; 68 | }; 69 | } 70 | 71 | export function createResource({ resource, id, opts }) { 72 | return (dispatch) => dispatch(executeFetch({ 73 | resource, id, opts, actionType: 'CREATE', 74 | })); 75 | } 76 | 77 | export function updateResource({ resource, id, opts }) { 78 | return (dispatch) => dispatch(executeFetch({ 79 | resource, id, opts, actionType: 'UPDATE', 80 | })); 81 | } 82 | 83 | export function updateCollection({ resource, id, opts }) { 84 | return (dispatch) => dispatch(executeFetch({ 85 | resource, id, opts, actionType: 'UPDATE_COLLECTION', 86 | })); 87 | } 88 | 89 | export function destroyResource({ resource, id, opts }) { 90 | return (dispatch) => dispatch(executeFetch({ 91 | resource, id, opts, actionType: 'DESTROY', 92 | })); 93 | } 94 | 95 | export function patchResource({ resource, id, opts }) { 96 | return (dispatch) => dispatch(executeFetch({ 97 | resource, id, opts, actionType: 'PATCH', 98 | })); 99 | } 100 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "iguazu-rest", 3 | "version": "1.11.1", 4 | "description": "A Redux REST caching library that follows Iguazu patterns", 5 | "main": "lib/index.js", 6 | "files": [ 7 | "lib" 8 | ], 9 | "scripts": { 10 | "build": "babel src --out-dir lib", 11 | "prepare": "npm run build", 12 | "test": "npm run test:lint && npm run test:unit", 13 | "test:lint": "eslint --ignore-path .gitignore --ext js,jsx,md .", 14 | "test:lockfile": "lockfile-lint -p package-lock.json -t npm -a npm -o https: -c -i", 15 | "test:git-history": "commitlint --from origin/main --to HEAD", 16 | "test:unit": "jest", 17 | "posttest": "npm run test:git-history && npm run test:lockfile" 18 | }, 19 | "author": "Maia Teegarden", 20 | "contributors": [ 21 | "Andres Escobar (https://github.com/anescobar1991)", 22 | "James Singleton (https://github.com/JamesSingleton)", 23 | "Jamie King (https://github.com/10xLaCroixDrinker)", 24 | "Jonathan Adshead (https://github.com/JAdshead)", 25 | "Michael Tobia (https://github.com/Francois-Esquire)", 26 | "Michael Tomcal (https://github.com/mtomcal))", 27 | "Stephanie Coates (https://github.com/stephaniecoates)", 28 | "Nelly Kiboi (https://github.com/nellyk)", 29 | "Nickolas Oliver (https://github.com/PixnBits)", 30 | "Andrew Curtis (https://github.com/drewcur)", 31 | "Scott McIntyre (https://github.com/smackfu)" 32 | ], 33 | "license": "Apache-2.0", 34 | "repository": { 35 | "type": "git", 36 | "url": "https://github.com/americanexpress/iguazu-rest.git" 37 | }, 38 | "homepage": "https://github.com/americanexpress/iguazu-rest", 39 | "bugs": { 40 | "url": "https://github.com/americanexpress/iguazu-rest/issues" 41 | }, 42 | "keywords": [ 43 | "async", 44 | "react", 45 | "redux", 46 | "react-redux", 47 | "fetch", 48 | "data", 49 | "rest", 50 | "resource", 51 | "crud", 52 | "iguazu", 53 | "adapter" 54 | ], 55 | "jest": { 56 | "preset": "amex-jest-preset", 57 | "setupFiles": [ 58 | "./setupJest.js" 59 | ], 60 | "coveragePathIgnorePatterns": [ 61 | "./setupJest.js", 62 | "./commitlint.config.js" 63 | ] 64 | }, 65 | "dependencies": { 66 | "deepmerge": "^1.5.2", 67 | "immutable": "^3.8.2", 68 | "isomorphic-fetch": "^3.0.0", 69 | "object-hash": "^1.3.1" 70 | }, 71 | "devDependencies": { 72 | "@babel/cli": "^7.22.10", 73 | "@babel/core": "^7.22.10", 74 | "@babel/polyfill": "^7.12.1", 75 | "@commitlint/cli": "^8.3.6", 76 | "@commitlint/config-conventional": "^8.3.6", 77 | "@semantic-release/changelog": "^5.0.1", 78 | "@semantic-release/commit-analyzer": "^8.0.1", 79 | "@semantic-release/git": "^9.0.1", 80 | "@semantic-release/npm": "^7.1.3", 81 | "@semantic-release/release-notes-generator": "^9.0.3", 82 | "amex-jest-preset": "^6.1.2", 83 | "babel-jest": "^24.9.0", 84 | "babel-preset-amex": "^3.6.1", 85 | "core-js-compat": "3.4.5", 86 | "eslint": "^6.8.0", 87 | "eslint-config-amex": "^11.2.0", 88 | "husky": "^3.1.0", 89 | "jest": "^25.5.4", 90 | "jest-fetch-mock": "^1.7.5", 91 | "lockfile-lint": "^4.12.0", 92 | "react": "^16.14.0", 93 | "react-dom": "^16.14.0", 94 | "semantic-release": "^17.4.7" 95 | }, 96 | "release": { 97 | "branches": [ 98 | "+([0-9])?(.{+([0-9]),x}).x", 99 | "main", 100 | "next", 101 | "next-major", 102 | { 103 | "name": "beta", 104 | "prerelease": true 105 | }, 106 | { 107 | "name": "alpha", 108 | "prerelease": true 109 | } 110 | ], 111 | "plugins": [ 112 | "@semantic-release/commit-analyzer", 113 | "@semantic-release/release-notes-generator", 114 | "@semantic-release/changelog", 115 | "@semantic-release/npm", 116 | "@semantic-release/git", 117 | "@semantic-release/github" 118 | ] 119 | }, 120 | "husky": { 121 | "hooks": { 122 | "pre-commit": "npm test", 123 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS" 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /__tests__/helpers/url.spec.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import { buildFetchUrl } from '../../src/helpers/url'; 18 | 19 | describe('buildFetchUrl', () => { 20 | it('should handle a simple url with one id provided', () => { 21 | const baseUrl = 'http://api.domain.com/users/:id'; 22 | const url = buildFetchUrl({ url: baseUrl, id: '123' }); 23 | expect(url).toBe('http://api.domain.com/users/123'); 24 | }); 25 | 26 | it('should handle a simple url with one id that is not provided', () => { 27 | const baseUrl = 'http://api.domain.com/users/:id'; 28 | const url = buildFetchUrl({ url: baseUrl }); 29 | expect(url).toBe('http://api.domain.com/users'); 30 | }); 31 | 32 | it('should handle a nested url with all ids provided', () => { 33 | const baseUrl = 'http://api.domain.com/users/:userId/posts/:postId'; 34 | const url = buildFetchUrl({ url: baseUrl, id: { userId: '123', postId: 'abc' } }); 35 | expect(url).toBe('http://api.domain.com/users/123/posts/abc'); 36 | }); 37 | 38 | it('should handle a nested url with some ids provided', () => { 39 | const baseUrl = 'http://api.domain.com/users/:userId/posts/:postId'; 40 | const url = buildFetchUrl({ url: baseUrl, id: { userId: '123' } }); 41 | expect(url).toBe('http://api.domain.com/users/123/posts'); 42 | }); 43 | 44 | it('should handle accidentally passing more ids than necessary', () => { 45 | const baseUrl = 'http://api.domain.com/users/:userId/posts/:postId'; 46 | const url = buildFetchUrl({ url: baseUrl, id: { userId: '123', someId: 'huh' } }); 47 | expect(url).toBe('http://api.domain.com/users/123/posts'); 48 | }); 49 | 50 | it('should handle empty optional ids by removing extra forward slashes or question marks', () => { 51 | const baseUrl = 'http://api.domain.com/users/:userId?/posts/:postId'; 52 | const url = buildFetchUrl({ url: baseUrl, id: { someId: 'huh' } }); 53 | expect(url).toBe('http://api.domain.com/users/posts'); 54 | }); 55 | 56 | it('should handle non-empty optional ids', () => { 57 | const baseUrl = 'http://api.domain.com/users/:userId?/posts/:postId'; 58 | const url = buildFetchUrl({ url: baseUrl, id: { userId: '123', someId: 'huh' } }); 59 | expect(url).toBe('http://api.domain.com/users/123/posts'); 60 | }); 61 | 62 | it('omits `:user?` when id field is not passed', () => { 63 | const baseUrl = 'http://api.domain.com/users/:user?/comments'; 64 | const url = buildFetchUrl({ 65 | url: baseUrl, 66 | opts: { 67 | query: { someModifier: 'questionable?' }, 68 | }, 69 | }); 70 | expect(url).toBe('http://api.domain.com/users/comments?someModifier=questionable?'); 71 | }); 72 | 73 | it('should add query params', () => { 74 | const baseUrl = 'http://api.domain.com/users/:userId'; 75 | const url = buildFetchUrl({ 76 | url: baseUrl, 77 | opts: { 78 | query: { 79 | a: 'b', 80 | x: 'y', 81 | }, 82 | }, 83 | }); 84 | expect(url).toBe('http://api.domain.com/users?a=b&x=y'); 85 | }); 86 | 87 | it('should replace query params with the correct value', () => { 88 | const baseUrl = 'http://api.domain.com/users/:userId?a=y&x=b'; 89 | const url = buildFetchUrl({ 90 | url: baseUrl, 91 | opts: { 92 | query: { 93 | a: 'b', 94 | x: 'y', 95 | }, 96 | }, 97 | }); 98 | expect(url).toBe('http://api.domain.com/users?a=b&x=y'); 99 | }); 100 | 101 | it('should handle id params as query params', () => { 102 | const baseUrl = 'http://api.domain.com/users?userId=:id'; 103 | const url = buildFetchUrl({ 104 | url: baseUrl, 105 | id: '123', 106 | }); 107 | expect(url).toBe('http://api.domain.com/users?userId=123'); 108 | }); 109 | }); 110 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to iguazu-rest 2 | 3 | ✨ Thank you for taking the time to contribute to this project ✨ 4 | 5 | ## 📖 Table of Contents 6 | 7 | * [Code of Conduct](#code-of-conduct) 8 | * [Developing](#developing) 9 | * [Submitting a new feature](#submitting-a-new-feature) 10 | * [Reporting bugs](#reporting-bugs) 11 | * [Contributing](#getting-in-contact) 12 | * [Coding conventions](#coding-conventions) 13 | 14 | ## Code of Conduct 15 | 16 | This project adheres to the American Express [Code of Conduct](./CODE_OF_CONDUCT.md). By contributing, you are expected to honor these guidelines. 17 | 18 | ## Developing 19 | 20 | ### Installation 21 | 22 | 23 | 1. Fork the repository `iguazu-rest` to your GitHub account. 24 | 2. Afterwards run the following commands in your terminal 25 | 26 | ```bash 27 | $ git clone https://github.com//iguazu-rest 28 | $ cd iguazu-rest 29 | ``` 30 | 31 | > replace `your-github-username` with your github username 32 | 33 | 3. Install the dependencies by running 34 | 35 | ```bash 36 | $ npm install 37 | ``` 38 | 39 | 4. You can now run any of these scripts from the root folder. 40 | 41 | #### Running and cleaning the build files 42 | 43 | - **`npm run build`** 44 | 45 | Runs `babel` to compile `src` files to transpiled JavaScript into `lib` using 46 | [`babel-preset-amex`](https://github.com/americanexpress/babel-preset-amex). 47 | 48 | #### Running tests 49 | 50 | - **`npm run lint`** 51 | 52 | Verifies that your code matches the American Express code style defined in 53 | [`eslint-config-amex`](https://github.com/americanexpress/eslint-config-amex). 54 | 55 | - **`npm test`** 56 | 57 | Runs unit tests **and** verifies the format of all commit messages on the current branch. 58 | 59 | - **`npm posttest`** 60 | 61 | Runs linting on the current branch, checks that the commits follow [conventional commits](https://www.conventionalcommits.org/) and verifies that the `package-lock.json` file includes public NPM registry URLs. 62 | 63 | ## Submitting a new feature 64 | 65 | When submitting a new feature request or enhancement of an existing feature please review the following: 66 | 67 | ### Is your feature request related to a problem 68 | 69 | Please provide a clear and concise description of what you want and what your use case is. 70 | 71 | ### Provide an example 72 | 73 | Please include a snippets of the code of the new feature. 74 | 75 | ### Describe the suggested enhancement 76 | 77 | A clear and concise description of the enhancement to be added include a step-by-step guide if applicable. 78 | Add any other context or screenshots or animated GIFs about the feature request 79 | 80 | ### Describe alternatives you've considered 81 | 82 | A clear and concise description of any alternative solutions or features you've considered. 83 | 84 | ## Reporting bugs 85 | 86 | All issues are submitted within GitHub issues. Please check this before submitting a new issue. 87 | 88 | ### Describe the bug 89 | 90 | A clear and concise description of what the bug is. 91 | 92 | ### Provide step-by-step guide on how to reproduce the bug 93 | 94 | Steps to reproduce the behavior, please provide code snippets or a link to repository 95 | 96 | ### Expected behavior 97 | 98 | Please provide a description of the expected behavior 99 | 100 | ### Screenshots 101 | 102 | If applicable, add screenshots or animated GIFs to help explain your problem. 103 | 104 | ### System information 105 | 106 | Provide the system information which is not limited to the below: 107 | 108 | - Browser (if applies) [e.g. chrome, safari] 109 | - Version of iguazu-rest: [e.g. 5.0.0] 110 | - Node version:[e.g 10.15.1] 111 | 112 | ### Security Bugs 113 | 114 | Please review our [Security Policy](./SECURITY.md). Please follow the instructions outlined in the policy. 115 | 116 | ## Getting in contact 117 | 118 | - Join our [Slack channel](https://one-amex.slack.com) request an invite [here](https://join.slack.com/t/one-amex/shared_invite/enQtOTA0MzEzODExODEwLTlmYzI1Y2U2ZDEwNWJjOTAxYTlmZTYzMjUyNzQyZTdmMWIwZGJmZDM2MDZmYzVjMDk5OWU4OGIwNjJjZWRhMjY) 119 | 120 | ## Coding conventions 121 | 122 | ### Git Commit Guidelines 123 | 124 | We follow [conventional commits](https://www.conventionalcommits.org/) for git commit message formatting. These rules make it easier to review commit logs and improve contextual understanding of code changes. This also allows us to auto-generate the CHANGELOG from commit messages. 125 | -------------------------------------------------------------------------------- /src/helpers/url.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | // https://github.com/angular/angular.js/blob/master/src/ngResource/resource.js#L473 18 | 19 | const PROTOCOL_AND_DOMAIN_REGEX = /^https?:\/\/[^/]*/; 20 | const NUMBER_REGEX = /^\\d+$/; 21 | // const isString = string => typeof string === 'string'; 22 | 23 | /** 24 | * This method is intended for encoding *key* or *value* parts of query component. We need a 25 | * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't 26 | * have to be encoded per http://tools.ietf.org/html/rfc3986 27 | */ 28 | export const encodeUriQuery = (val) => encodeURIComponent(val) 29 | .replace(/%40/gi, '@') 30 | .replace(/%3A/gi, ':') 31 | .replace(/%24/g, '$') 32 | .replace(/%2C/gi, ','); 33 | 34 | /** 35 | * We need our custom method because encodeURIComponent is too aggressive and doesn't follow 36 | * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set 37 | * (pchar) allowed in path segments 38 | */ 39 | export const encodeUriSegment = (val) => encodeUriQuery(val) 40 | .replace(/%26/gi, '&') 41 | .replace(/%3D/gi, '=') 42 | .replace(/%2B/gi, '+'); 43 | 44 | export const parseUrlParams = (url) => url.split(/\W/).reduce((urlParams, param) => { 45 | if (!NUMBER_REGEX.test(param) && param && new RegExp(`(^|[^\\\\]):${param}(\\W|$)`).test(url)) { 46 | urlParams[param] = { // eslint-disable-line no-param-reassign 47 | isQueryParamValue: new RegExp(`\\?.*=:${param}(?:\\W|$)`).test(url), 48 | }; 49 | } 50 | return urlParams; 51 | }, {}); 52 | 53 | export const replaceUrlParamFromUrl = (url, urlParam, replace = '') => url.replace(new RegExp(`(/?):${urlParam}(\\W|$)`, 'g'), (match, leadingSlashes, tail) => (replace || tail.charAt(0) === '/' ? leadingSlashes : '') + replace + tail 54 | ); 55 | 56 | export const replaceQueryStringParamFromUrl = (url, key, value) => { 57 | const re = new RegExp(`([?&])${key}=.*?(&|$)`, 'i'); 58 | const sep = url.indexOf('?') !== -1 ? '&' : '?'; 59 | return url.match(re) 60 | ? url.replace(re, `$1${key}=${value}$2`) 61 | : `${url}${sep}${key}=${value}`; 62 | }; 63 | 64 | export const splitUrlByProtocolAndDomain = (url) => { 65 | let protocolAndDomain; 66 | const remainderUrl = url.replace(PROTOCOL_AND_DOMAIN_REGEX, (match) => { 67 | protocolAndDomain = match; 68 | return ''; 69 | }); 70 | return [protocolAndDomain, remainderUrl]; 71 | }; 72 | 73 | const isObject = (maybeObject) => typeof maybeObject === 'object'; 74 | 75 | export function addQueryParams({ url, opts = {} }) { 76 | return Object.keys(opts.query || []).reduce((wipUrl, queryParam) => { 77 | const queryParamValue = opts.query[queryParam]; 78 | return replaceQueryStringParamFromUrl(wipUrl, queryParam, queryParamValue); 79 | }, url); 80 | } 81 | 82 | export function replaceUrlParams({ url, id }) { 83 | // Replace urlParams with values from context 84 | const urlParams = parseUrlParams(url); 85 | 86 | return Object.keys(urlParams).reduce((wipUrl, urlParam) => { 87 | const urlParamInfo = urlParams[urlParam]; 88 | const idAsObject = !isObject(id) ? { id } : id; 89 | const value = idAsObject[urlParam] || ''; 90 | if (value) { 91 | const encodedValue = urlParamInfo.isQueryParamValue 92 | ? encodeUriQuery(value) : encodeUriSegment(value); 93 | return replaceUrlParamFromUrl(wipUrl, urlParam, encodedValue); 94 | } 95 | return replaceUrlParamFromUrl(wipUrl, urlParam); 96 | }, url) 97 | .replace(/\/+$/, ''); // strip trailing slashes 98 | } 99 | 100 | export function buildFetchUrl({ url, id, opts }) { 101 | const [protocolAndDomain, remainderUrl] = splitUrlByProtocolAndDomain(url); 102 | 103 | let builtUrl = replaceUrlParams({ url: remainderUrl, id }).replace(/\?\//g, '/'); 104 | builtUrl = addQueryParams({ url: builtUrl, opts }); 105 | 106 | return protocolAndDomain + builtUrl; 107 | } 108 | -------------------------------------------------------------------------------- /__tests__/helpers/hash.spec.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import { getResourceIdHash, getCollectionIdHash, getQueryHash } from '../../src/helpers/hash'; 18 | import { ID_TYPE_ERROR } from '../../src/errors'; 19 | 20 | describe('hash helpers', () => { 21 | describe('getResourceIdHash', () => { 22 | it('should consistently return the same hash for the same id string', () => { 23 | expect(getResourceIdHash('abc123')).toEqual(getResourceIdHash('abc123')); 24 | }); 25 | 26 | it('should consistently return the same hash for the same id object', () => { 27 | expect(getResourceIdHash({ id: 'abc123', nestedId: 'xyz789' })) 28 | .toEqual(getResourceIdHash({ nestedId: 'xyz789', id: 'abc123' })); 29 | }); 30 | 31 | it('should return the same hash if you send in the id as a string or an object', () => { 32 | expect(getResourceIdHash('123')).toEqual(getResourceIdHash({ id: '123' })); 33 | }); 34 | 35 | it('should return the same hash if you send in the id value as a string or a number', () => { 36 | expect(getResourceIdHash(123)).toEqual(getResourceIdHash('123')); 37 | expect(getResourceIdHash({ id: 123 })).toEqual(getResourceIdHash({ id: '123' })); 38 | }); 39 | 40 | describe('when type of id is invalid', () => { 41 | it('should throw an error when the id is null', () => { 42 | expect(() => getResourceIdHash(null)).toThrowError( 43 | new Error(ID_TYPE_ERROR) 44 | ); 45 | }); 46 | it('should throw an error when the id is undefined', () => { 47 | expect(() => getResourceIdHash(undefined)).toThrowError( 48 | new Error(ID_TYPE_ERROR) 49 | ); 50 | }); 51 | it('should throw an error when the id is a boolean', () => { 52 | expect(() => getResourceIdHash(false)).toThrowError( 53 | new Error(ID_TYPE_ERROR) 54 | ); 55 | }); 56 | it('should throw an error when the id is a function', () => { 57 | expect(() => getResourceIdHash(() => '42')).toThrowError( 58 | new Error(ID_TYPE_ERROR) 59 | ); 60 | }); 61 | }); 62 | }); 63 | 64 | describe('getCollectionIdHash', () => { 65 | it('should return the same hash for a simple collection', () => { 66 | expect(getCollectionIdHash()).toEqual(getCollectionIdHash()); 67 | }); 68 | 69 | it('should return the same hash for a nested collection', () => { 70 | expect(getCollectionIdHash({ nestedId: 'xyz789' })) 71 | .toEqual(getCollectionIdHash({ nestedId: 'xyz789' })); 72 | }); 73 | 74 | it('should return the same hash for resources that belong to the same collection', () => { 75 | expect(getCollectionIdHash({ id: 'abc123', nestedId: 'xyz789' })) 76 | .toEqual(getCollectionIdHash({ nestedId: 'xyz789', id: 'lmnop456' })); 77 | expect(getCollectionIdHash('abc123')).toEqual(getCollectionIdHash({ id: 'lmnop456' })); 78 | }); 79 | 80 | describe('when type of id is invalid', () => { 81 | it('should throw an error when the id is a boolean and true', () => { 82 | expect(() => getCollectionIdHash(true)).toThrowError( 83 | new Error(ID_TYPE_ERROR) 84 | ); 85 | }); 86 | it('should throw an error when the id is a function', () => { 87 | expect(() => getCollectionIdHash(() => '42')).toThrowError( 88 | new Error(ID_TYPE_ERROR) 89 | ); 90 | }); 91 | }); 92 | }); 93 | 94 | describe('getQueryHash', () => { 95 | it('should handle empty opts', () => { 96 | expect(getQueryHash()).toEqual(getQueryHash()); 97 | }); 98 | 99 | it('should handle empty query', () => { 100 | expect(getQueryHash({})).toEqual(getQueryHash({})); 101 | expect(getQueryHash({})).toEqual(getQueryHash()); 102 | }); 103 | 104 | it('should support a populated query object', () => { 105 | expect(getQueryHash({ query: { some: 'query' } })) 106 | .toEqual(getQueryHash({ query: { some: 'query' } })); 107 | }); 108 | }); 109 | }); 110 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ### American Express Open Source Community Guidelines 2 | 3 | #### Last Modified: January 29, 2016 4 | 5 | Welcome to the American Express Open Source Community on GitHub! These American Express Community Guidelines outline our expectations for Github participating members within the American Express community, as well as steps for reporting unacceptable behavior. We are committed to providing a welcoming and inspiring community for all and expect our community Guidelines to be honored. 6 | 7 | **IMPORTANT REMINDER:** 8 | 9 | When you visit American Express on any third party sites such as GitHub your activity there is subject to that site’s then current terms of use., along with their privacy and data security practices and policies. The Github platform is not affiliated with us and may have practices and policies that are different than are our own. 10 | Please note, American Express is not responsible for, and does not control, the GitHub site’s terms of use, privacy and data security practices and policies. You should, therefore, always exercise caution when posting, sharing or otherwise taking any action on that site and, of course, on the Internet in general. 11 | Our open source community strives to: 12 | - **Be friendly and patient**. 13 | - **Be welcoming**: We strive to be a community that welcomes and supports people of all 14 | backgrounds and identities. This includes, but is not limited to members of any race, ethnicity, culture, national origin, color, immigration status, social and economic class, educational level, sex, sexual orientation, gender identity and expression, age, size, family status, political belief, religion, and mental and physical ability. 15 | - **Be considerate**: Your work will be used by other people, and you in turn will depend on the work of others. Any decision you take will affect users and colleagues, and you should take those consequences into account when making decisions. Remember that we're a world-wide community, so you might not be communicating in someone else's primary language. 16 | - **Be respectful**: Not all of us will agree all the time, but disagreement is no excuse for poor behavior and poor manners. We might all experience some frustration now and then, but we cannot allow that frustration to turn into a personal attack. It’s important to remember that a community where people feel uncomfortable or threatened is not a productive one. 17 | - **Be careful in the words that we choose**: We are a community of professionals, and we conduct ourselves professionally. Be kind to others. Do not insult or put down other participants. Harassment and other exclusionary behavior aren't acceptable. 18 | - **Try to understand why we disagree**: Disagreements, both social and technical, happen all the time. It is important that we resolve disagreements and differing views constructively. Remember that we’re all different people. The strength of our community comes from its diversity, people from a wide range of backgrounds. Different people have different perspectives on issues. Being unable to understand why someone holds a viewpoint doesn’t mean that they’re wrong. Don’t forget that it is human to err and blaming each other doesn’t get us anywhere. Instead, focus on helping to resolve issues and learning from mistakes. 19 | 20 | ### Definitions 21 | Harassment includes, but is not limited to: 22 | - Offensive comments related to gender, gender identity and expression, sexual orientation, disability, mental illness, neuro(a)typicality, physical appearance, body size, race, age, regional discrimination, political or religious affiliation 23 | - Unwelcome comments regarding a person’s lifestyle choices and practices, including those related to food, health, parenting, drugs, and employment 24 | - Deliberate misgendering. This includes deadnaming or persistently using a pronoun that does not correctly reflect a person's gender identity. You must address people by the name they give you when not addressing them by their username or handle 25 | - Physical contact and simulated physical contact (eg, textual descriptions like “hug” or “backrub”) without consent or after a request to stop 26 | - Threats of violence, both physical and psychological 27 | - Incitement of violence towards any individual, including encouraging a person to commit suicide 28 | or to engage in self-harm 29 | - Deliberate intimidation 30 | - Stalking or following 31 | - Harassing photography or recording, including logging online activity for harassment purposes 32 | - Sustained disruption of discussion 33 | - Unwelcome sexual attention, including gratuitous or off-topic sexual images or behaviour 34 | - Pattern of inappropriate social contact, such as requesting/assuming inappropriate levels of 35 | intimacy with others 36 | - Continued one-on-one communication after requests to cease 37 | - Deliberate “outing” of any aspect of a person’s identity without their consent except as necessary 38 | to protect others from intentional abuse 39 | - Publication of non-harassing private communication 40 | 41 | Our open source community prioritizes marginalized people’s safety over privileged people’s comfort. We will not act on complaints regarding: 42 | - ‘Reverse’ -isms, including ‘reverse racism,’ ‘reverse sexism,’ and ‘cisphobia’ 43 | - Reasonable communication of boundaries, such as “leave me alone,” “go away,” or “I’m not 44 | discussing this with you” 45 | - Refusal to explain or debate social justice concepts 46 | - Communicating in a ‘tone’ you don’t find congenial 47 | - Criticizing racist, sexist, cissexist, or otherwise oppressive behavior or assumptions 48 | 49 | ### Diversity Statement 50 | We encourage everyone to participate and are committed to building a community for all. Although we will fail at times, we seek to treat everyone both as fairly and equally as possible. Whenever a participant has made a mistake, we expect them to take responsibility for it. If someone has been harmed or offended, it is our responsibility to listen carefully and respectfully, and do our best to right the wrong. 51 | 52 | Although this list cannot be exhaustive, we explicitly honor diversity in age, gender, gender identity or expression, culture, ethnicity, language, national origin, political beliefs, profession, race, religion, sexual orientation, socioeconomic status, and technical ability. We will not tolerate discrimination based on any of the protected characteristics above, including participants with disabilities. 53 | 54 | ### Reporting Issues 55 | If you experience or witness unacceptable behavior—or have any other concerns—please report it by contacting us at opensource@aexp.com. All reports will be handled with discretion. In your report please include: 56 | - Your contact information. 57 | - Names (real, nicknames, or pseudonyms) of any individuals involved. If there are additional 58 | witnesses, please include them as well. Your account of what occurred, and if you believe the incident is ongoing. If there is a publicly available record (e.g. a mailing list archive or a public IRC logger), please include a link. 59 | - Any additional information that may be helpful. 60 | 61 | After filing a report, a representative of our community will contact you personally, review the incident, follow up with any additional questions, and make a decision as to how to respond. If the person who is harassing you is part of the response team, they will recuse themselves from handling your incident. If the complaint originates from a member of the response team, it will be handled by a different member of the response team. We will respect confidentiality requests for the purpose of protecting victims of abuse. 62 | 63 | ### Removal of Posts 64 | We will not review every comment or post, but we reserve the right to remove any that violates these Guidelines or that, in our sole discretion, we otherwise consider objectionable and we may ban offenders from our community. 65 | 66 | ### Suspension/Termination/Reporting to Authority 67 | In certain instances, we may suspend, terminate or ban certain repeat offenders and/or those committing significant violations of these Guidelines. When appropriate, we may also, on our own or as required by the GitHub terms of use, be required to refer and/or work with GitHub and/or the appropriate authorities to review and/or pursue certain violations. 68 | 69 | ### Attribution & Acknowledgements 70 | These Guidelines have been adapted from the [Code of Conduct of the TODO group](http://todogroup.org/opencodeofconduct/). They are subject to revision by American Express and may be revised from time to time. 71 | 72 | Thank you for your participation! 73 | -------------------------------------------------------------------------------- /__tests__/actions/query.spec.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import { queryResource, queryCollection } from '../../src/actions/query'; 18 | 19 | const mockLoadPromise = Promise.resolve('data'); 20 | jest.mock('../../src/actions/crud', () => ({ 21 | loadResource: jest.fn(() => mockLoadPromise), 22 | loadCollection: jest.fn(() => mockLoadPromise), 23 | })); 24 | 25 | jest.mock('../../src/selectors', () => ({ 26 | getResource: jest.fn(() => () => 'resource'), 27 | getCollection: jest.fn(() => () => 'collection'), 28 | getResourceIsLoaded: jest.fn(), 29 | getCollectionIsLoaded: jest.fn(), 30 | })); 31 | 32 | jest.mock('../../src/actions/asyncSideEffects', () => ({ 33 | handleQueryPromiseRejection: jest.fn((promise) => promise.catch(() => { /* swallow */ })), 34 | })); 35 | 36 | const dispatch = jest.fn((input) => input); 37 | const getState = () => 'state'; 38 | const resource = 'users'; 39 | const id = '123'; 40 | const opts = 'opts'; 41 | const loadError = new Error('Async Load Error'); 42 | 43 | describe('iguazu query actions', () => { 44 | afterEach(() => { 45 | jest.clearAllMocks(); 46 | }); 47 | 48 | describe('queryResource', () => { 49 | it('should return a loading response if the resource is loading', () => { 50 | require('../../src/selectors').getResourceIsLoaded.mockImplementationOnce(() => () => false); // eslint-disable-line global-require 51 | const thunk = queryResource({ resource, id, opts }); 52 | const loadResponse = thunk(dispatch, getState); 53 | expect(loadResponse.data).toEqual('resource'); 54 | expect(loadResponse.status).toEqual('loading'); 55 | expect(loadResponse.error).toBeFalsy(); 56 | expect(loadResponse.promise).toEqual(mockLoadPromise); 57 | }); 58 | 59 | it('should return a loaded response if the resource is loaded', () => { 60 | require('../../src/selectors').getResourceIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 61 | const thunk = queryResource({ resource, id, opts }); 62 | const loadResponse = thunk(dispatch, getState); 63 | expect(loadResponse.data).toEqual('resource'); 64 | expect(loadResponse.status).toEqual('complete'); 65 | expect(loadResponse.error).toBeFalsy(); 66 | expect(loadResponse.promise).toEqual(mockLoadPromise); 67 | }); 68 | 69 | it('should return a loading response if the resource is loaded, but forceFetch is specified', () => { 70 | require('../../src/selectors').getResourceIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 71 | const thunk = queryResource({ 72 | resource, id, opts, forceFetch: true, 73 | }); 74 | const loadResponse = thunk(dispatch, getState); 75 | expect(loadResponse.data).toEqual('resource'); 76 | expect(loadResponse.status).toEqual('loading'); 77 | expect(loadResponse.error).toBeFalsy(); 78 | expect(loadResponse.promise).toEqual(mockLoadPromise); 79 | }); 80 | 81 | it('should indicate an error occured if applicable', () => { 82 | require('../../src/selectors').getResourceIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 83 | require('../../src/selectors').getResource.mockImplementationOnce(() => () => loadError); // eslint-disable-line global-require 84 | const thunk = queryResource({ resource, id, opts }); 85 | const loadResponse = thunk(dispatch, getState); 86 | expect(loadResponse.error).toBe(loadError); 87 | }); 88 | 89 | it('should catch the promise if it rejects, but leave the uncaught promise for ssr', async () => { 90 | expect.assertions(2); 91 | const { handleQueryPromiseRejection } = require('../../src/actions/asyncSideEffects'); // eslint-disable-line global-require 92 | let promise; 93 | try { 94 | require('../../src/selectors').getResourceIsLoaded.mockImplementationOnce(() => () => false); // eslint-disable-line global-require 95 | require('../../src/actions/crud').loadResource.mockImplementationOnce(() => Promise.reject(new Error('async error'))); // eslint-disable-line global-require 96 | const thunk = queryResource({ resource, id, opts }); 97 | const loadResponse = thunk(dispatch, getState); 98 | promise = loadResponse.promise; 99 | await promise; 100 | } catch (e) { 101 | expect(handleQueryPromiseRejection).toHaveBeenCalledWith(promise); 102 | expect(e.message).toBe('async error'); 103 | } 104 | }); 105 | }); 106 | 107 | describe('queryCollection', () => { 108 | it('should return a loading response if the collection is loading', () => { 109 | require('../../src/selectors').getCollectionIsLoaded.mockImplementationOnce(() => () => false); // eslint-disable-line global-require 110 | const thunk = queryCollection({ resource, id, opts }); 111 | const loadResponse = thunk(dispatch, getState); 112 | expect(loadResponse.data).toEqual('collection'); 113 | expect(loadResponse.status).toEqual('loading'); 114 | expect(loadResponse.promise).toEqual(mockLoadPromise); 115 | }); 116 | 117 | it('should return a loaded response if the collection is loaded', () => { 118 | require('../../src/selectors').getCollectionIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 119 | const thunk = queryCollection({ resource, id, opts }); 120 | const loadResponse = thunk(dispatch, getState); 121 | expect(loadResponse.data).toEqual('collection'); 122 | expect(loadResponse.status).toEqual('complete'); 123 | expect(loadResponse.promise).toEqual(mockLoadPromise); 124 | }); 125 | 126 | it('should return a loading response if the collection is loaded, but forceFetch is specified', () => { 127 | require('../../src/selectors').getCollectionIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 128 | const thunk = queryCollection({ 129 | resource, id, opts, forceFetch: true, 130 | }); 131 | const loadResponse = thunk(dispatch, getState); 132 | expect(loadResponse.data).toEqual('collection'); 133 | expect(loadResponse.status).toEqual('loading'); 134 | expect(loadResponse.promise).toEqual(mockLoadPromise); 135 | }); 136 | 137 | it('should indicate an error occured if applicable', () => { 138 | require('../../src/selectors').getCollectionIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 139 | require('../../src/selectors').getCollection.mockImplementationOnce(() => () => loadError); // eslint-disable-line global-require 140 | const thunk = queryCollection({ resource, id, opts }); 141 | const loadResponse = thunk(dispatch, getState); 142 | expect(loadResponse.error).toBe(loadError); 143 | }); 144 | 145 | it('should catch the promise if it rejects, but leave the uncaught promise for ssr', async () => { 146 | expect.assertions(2); 147 | const { handleQueryPromiseRejection } = require('../../src/actions/asyncSideEffects'); // eslint-disable-line global-require 148 | let promise; 149 | try { 150 | require('../../src/selectors').getCollectionIsLoaded.mockImplementationOnce(() => () => false); // eslint-disable-line global-require 151 | require('../../src/actions/crud').loadCollection.mockImplementationOnce(() => Promise.reject(new Error('async error'))); // eslint-disable-line global-require 152 | const thunk = queryCollection({ resource, id, opts }); 153 | const loadResponse = thunk(dispatch, getState); 154 | promise = loadResponse.promise; 155 | await promise; 156 | } catch (e) { 157 | expect(handleQueryPromiseRejection).toHaveBeenCalledWith(promise); 158 | expect(e.message).toBe('async error'); 159 | } 160 | }); 161 | }); 162 | }); 163 | -------------------------------------------------------------------------------- /__tests__/selectors.spec.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import { fromJS } from 'immutable'; 18 | 19 | import { 20 | getResourceIdHash, 21 | getCollectionIdHash, 22 | getQueryHash, 23 | } from '../src/helpers/hash'; 24 | import { configureIguazuREST } from '../src/config'; 25 | 26 | import { 27 | getResourceIsLoaded, 28 | getResource, 29 | resourceIsLoading, 30 | getResourceLoadPromise, 31 | getCollectionIsLoaded, 32 | getCollection, 33 | collectionIsLoading, 34 | getCollectionLoadPromise, 35 | } from '../src/selectors'; 36 | 37 | const resource = 'users'; 38 | const id = '123'; 39 | const idHash = getResourceIdHash(id); 40 | 41 | describe('selectors', () => { 42 | beforeAll(() => { 43 | configureIguazuREST({ getToState: (state) => state.deep.resources }); 44 | }); 45 | 46 | describe('getResourceIsLoaded', () => { 47 | it('should return true if the resource is loaded', () => { 48 | const state = { 49 | deep: { 50 | resources: fromJS({ 51 | users: { items: { [idHash]: { id: '123', data: 'data' } } }, 52 | }), 53 | }, 54 | }; 55 | expect(getResourceIsLoaded({ resource, id })(state)).toBe(true); 56 | }); 57 | 58 | it('should return false if the resource is not loaded', () => { 59 | const state = { 60 | deep: { 61 | resources: fromJS({ 62 | users: { items: {} }, 63 | }), 64 | }, 65 | }; 66 | expect(getResourceIsLoaded({ resource, id })(state)).toBe(false); 67 | }); 68 | }); 69 | 70 | describe('getResource', () => { 71 | it('should return the resource as a pure JS', () => { 72 | const state = { 73 | deep: { 74 | resources: fromJS({ 75 | users: { items: { [idHash]: { id: '123', data: 'data' } } }, 76 | }), 77 | }, 78 | }; 79 | expect(getResource({ resource, id })(state)).toEqual({ id: '123', data: 'data' }); 80 | }); 81 | 82 | it('should return undefined if the resource is not loaded', () => { 83 | const state = { 84 | deep: { 85 | resources: fromJS({ 86 | users: { items: {} }, 87 | }), 88 | }, 89 | }; 90 | expect(getResource({ resource, id })(state)).toBeUndefined(); 91 | }); 92 | 93 | it('should get resource by id object', () => { 94 | const idObj = { id: 123, param1: 'a', param2: 'b' }; 95 | const idObjHash = getResourceIdHash(idObj); 96 | const state = { 97 | deep: { 98 | resources: fromJS({ 99 | users: { items: { [idObjHash]: { id: '123', data: 'data' } } }, 100 | }), 101 | }, 102 | }; 103 | expect(getResource({ resource, id: idObj })(state)).toEqual({ id: '123', data: 'data' }); 104 | }); 105 | 106 | it('should return an error if the resource failed to load', () => { 107 | const error = new Error('resource failed to load'); 108 | const state = { 109 | deep: { 110 | resources: fromJS({ 111 | users: { error: { [idHash]: error } }, 112 | }), 113 | }, 114 | }; 115 | expect(getResource({ resource, id })(state)).toBe(error); 116 | }); 117 | }); 118 | 119 | describe('resourceIsLoading', () => { 120 | it('should return true if the resource is loading', () => { 121 | const promise = Promise.resolve(); 122 | const state = { 123 | deep: { 124 | resources: fromJS({ 125 | users: { loading: { [idHash]: promise } }, 126 | }), 127 | }, 128 | }; 129 | expect(resourceIsLoading({ resource, id })(state)).toBe(true); 130 | }); 131 | 132 | it('should return true if the resource is loaded with error', () => { 133 | const error = new Error('resource failed to load'); 134 | const state = { 135 | deep: { 136 | resources: fromJS({ 137 | users: { error: { [idHash]: error } }, 138 | }), 139 | }, 140 | }; 141 | expect(getResourceIsLoaded({ resource, id })(state)).toBe(true); 142 | }); 143 | 144 | it('should return false if the resource is not loading', () => { 145 | const state = { 146 | deep: { 147 | resources: fromJS({ 148 | users: { loading: {} }, 149 | }), 150 | }, 151 | }; 152 | expect(resourceIsLoading({ resource, id })(state)).toBe(false); 153 | }); 154 | }); 155 | 156 | describe('getResourceLoadPromise', () => { 157 | it('should return the load promise for the resource', () => { 158 | const promise = Promise.resolve(); 159 | const state = { 160 | deep: { 161 | resources: fromJS({ 162 | users: { loading: { [idHash]: promise } }, 163 | }), 164 | }, 165 | }; 166 | expect(getResourceLoadPromise({ resource, id })(state)).toBe(promise); 167 | }); 168 | }); 169 | 170 | describe('getCollectionIsLoaded', () => { 171 | it('should return true if the collection is loaded', () => { 172 | const collectionIdHash = getCollectionIdHash(); 173 | const queryHash = getQueryHash(); 174 | const state = { 175 | deep: { 176 | resources: fromJS({ 177 | users: { collections: { [collectionIdHash]: { [queryHash]: ['123'] } } }, 178 | }), 179 | }, 180 | }; 181 | expect(getCollectionIsLoaded({ resource })(state)).toBe(true); 182 | }); 183 | 184 | it('should return true if the collection is loaded with error', () => { 185 | const collectionIdHash = getCollectionIdHash(); 186 | const queryHash = getQueryHash(); 187 | const error = new Error('resource failed to load'); 188 | const state = { 189 | deep: { 190 | resources: fromJS({ 191 | users: { 192 | collections: { 193 | [collectionIdHash]: { 194 | [queryHash]: { 195 | error, 196 | }, 197 | }, 198 | }, 199 | }, 200 | }), 201 | }, 202 | }; 203 | expect(getCollectionIsLoaded({ resource })(state)).toBe(true); 204 | }); 205 | 206 | it('should return false if the collection is not loaded', () => { 207 | const state = { 208 | deep: { 209 | resources: fromJS({ 210 | users: { loaded: {} }, 211 | }), 212 | }, 213 | }; 214 | expect(getCollectionIsLoaded({ resource })(state)).toBe(false); 215 | }); 216 | }); 217 | 218 | describe('getCollection', () => { 219 | it('should return the collection of resources in a pure JS array', () => { 220 | const collectionIdHash = getCollectionIdHash(); 221 | const queryHash = getQueryHash(); 222 | const state = { 223 | deep: { 224 | resources: fromJS({ 225 | users: { 226 | items: { 123: { id: '123', data: 'data' } }, 227 | collections: { [collectionIdHash]: { [queryHash]: { associatedIds: ['123'] } } }, 228 | }, 229 | }), 230 | }, 231 | }; 232 | expect(getCollection({ resource })(state)).toEqual([{ id: '123', data: 'data' }]); 233 | }); 234 | 235 | it('should return the collection load error if it failed to load', () => { 236 | const collectionIdHash = getCollectionIdHash(); 237 | const queryHash = getQueryHash(); 238 | const error = new Error('resource failed to load'); 239 | const state = { 240 | deep: { 241 | resources: fromJS({ 242 | users: { 243 | collections: { 244 | [collectionIdHash]: { 245 | [queryHash]: { 246 | error, 247 | }, 248 | }, 249 | }, 250 | }, 251 | }), 252 | }, 253 | }; 254 | expect(getCollection({ resource })(state)).toEqual(error); 255 | }); 256 | }); 257 | 258 | describe('collectionIsLoading', () => { 259 | it('should return true if the collection is loading', () => { 260 | const promise = Promise.resolve(); 261 | const collectionIdHash = getCollectionIdHash(); 262 | const queryHash = getQueryHash(); 263 | const state = { 264 | deep: { 265 | resources: fromJS({ 266 | users: { loading: { [collectionIdHash]: { [queryHash]: promise } } }, 267 | }), 268 | }, 269 | }; 270 | expect(collectionIsLoading({ resource })(state)).toBe(true); 271 | }); 272 | 273 | it('should return false if the collection is not loading', () => { 274 | const state = { 275 | deep: { 276 | resources: fromJS({ 277 | users: { loading: {} }, 278 | }), 279 | }, 280 | }; 281 | expect(collectionIsLoading({ resource })(state)).toBe(false); 282 | }); 283 | }); 284 | 285 | describe('getCollectionLoadPromise', () => { 286 | it('should return the load promise for the collection', () => { 287 | const promise = Promise.resolve(); 288 | const collectionIdHash = getCollectionIdHash(); 289 | const queryHash = getQueryHash(); 290 | const state = { 291 | deep: { 292 | resources: fromJS({ 293 | users: { loading: { [collectionIdHash]: { [queryHash]: promise } } }, 294 | }), 295 | }, 296 | }; 297 | expect(getCollectionLoadPromise({ resource })(state)).toBe(promise); 298 | }); 299 | }); 300 | }); 301 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 American Express Travel Related Services Company, Inc. 190 | 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /__tests__/actions/executeFetch.spec.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import config from '../../src/config'; 18 | import * as types from '../../src/types'; 19 | 20 | import executeFetch from '../../src/actions/executeFetch'; 21 | 22 | jest.mock('../../src/actions/asyncSideEffects', () => ({ 23 | waitAndDispatchFinished: jest.fn(() => 'waitAndDispatchFinishedThunk'), 24 | })); 25 | 26 | Date.now = jest.fn(() => 'now'); 27 | const dispatch = jest.fn(); 28 | const getState = () => {}; 29 | const resource = 'users'; 30 | const id = '123'; 31 | const opts = { some: 'opt' }; 32 | 33 | describe('executeFetch', () => { 34 | afterEach(() => { 35 | fetch.resetMocks(); 36 | jest.clearAllMocks(); 37 | }); 38 | 39 | describe('default behavior', () => { 40 | it('should handle an ok response', async () => { 41 | Object.assign(config, { 42 | defaultOpts: { default: 'opt' }, 43 | resources: { 44 | users: { 45 | fetch: () => ({ 46 | url: 'http://api.domain.com/users/:id', 47 | opts: { 48 | resource: 'opt', 49 | }, 50 | }), 51 | }, 52 | }, 53 | }); 54 | fetch.mockResponseOnce( 55 | JSON.stringify({ id: '123', name: 'joe' }), 56 | { status: 200, headers: { 'Content-Type': 'application/json' } } 57 | ); 58 | const thunk = executeFetch({ 59 | resource, id, opts, actionType: 'LOAD', 60 | }); 61 | const data = await thunk(dispatch, getState); 62 | expect(data).toEqual({ id: '123', name: 'joe' }); 63 | expect(fetch).toHaveBeenCalledWith( 64 | 'http://api.domain.com/users/123', 65 | { 66 | default: 'opt', method: 'GET', resource: 'opt', some: 'opt', 67 | } 68 | ); 69 | const promise = Promise.resolve(data); 70 | expect(dispatch).toHaveBeenCalledWith({ 71 | type: types.LOAD_STARTED, 72 | resource, 73 | id, 74 | opts, 75 | promise, 76 | }); 77 | expect(dispatch).toHaveBeenCalledWith('waitAndDispatchFinishedThunk'); 78 | }); 79 | 80 | it('should handle bad response', async () => { 81 | Object.assign(config, { 82 | defaultOpts: undefined, 83 | resources: { 84 | users: { 85 | fetch: () => ({ 86 | url: 'http://api.domain.com/users/:id', 87 | }), 88 | }, 89 | }, 90 | }); 91 | fetch.mockResponseOnce('body', { status: 500, statusText: 'Internal Server Error', url: 'url' }); 92 | const error = new Error('Internal Server Error (url)'); 93 | const promise = Promise.reject(error); 94 | const thunk = executeFetch({ resource, actionType: 'LOAD_COLLECTION' }); 95 | try { 96 | await thunk(dispatch, getState); 97 | } catch (e) { 98 | expect(dispatch).toHaveBeenCalledWith({ 99 | type: types.LOAD_COLLECTION_STARTED, 100 | resource, 101 | promise, 102 | }); 103 | expect(dispatch).toHaveBeenCalledWith('waitAndDispatchFinishedThunk'); 104 | expect(e).toEqual(error); 105 | expect(e.status).toEqual(500); 106 | expect(e.body).toEqual('body'); 107 | promise.catch(() => 'caught promise error'); // catch promise so unhandled promise doesn't show up in console 108 | } 109 | }); 110 | 111 | it('should use a data transformer if one is configured', async () => { 112 | Object.assign(config, { 113 | resources: { 114 | users: { 115 | fetch: () => ({ url: 'http://api.domain.com/users/:id' }), 116 | transformData: (data, { actionType }) => (actionType === 'LOAD_COLLECTION' ? data.actualCollection : data), 117 | }, 118 | }, 119 | }); 120 | fetch.mockResponseOnce( 121 | JSON.stringify({ 122 | some: 'meta', 123 | actualCollection: [{ id: '123', name: 'joe' }], 124 | }), 125 | { status: 200, headers: { 'Content-Type': 'application/json' } } 126 | ); 127 | const thunk = executeFetch({ 128 | resource, id, opts, actionType: 'LOAD_COLLECTION', 129 | }); 130 | const data = await thunk(dispatch, getState); 131 | expect(data).toEqual([{ id: '123', name: 'joe' }]); 132 | }); 133 | }); 134 | describe('fetchClient', () => { 135 | // Helpers and Mocks 136 | let fetchClient; 137 | const setupFetchMock = () => { 138 | Object.assign(config, { 139 | // Create the mock once called 140 | baseFetch: jest.fn((...args) => fetch.mockResponseOnce( 141 | JSON.stringify({ id: '1234', name: 'bill' }), 142 | { status: 200, headers: { 'Content-Type': 'application/json' } } 143 | )(...args)), 144 | defaultOpts: { default: 'opt' }, 145 | resources: { 146 | users: { 147 | fetch: () => ({ 148 | url: 'http://api.domain.com/users/:id', 149 | opts: { 150 | resource: 'opt', 151 | }, 152 | }), 153 | }, 154 | }, 155 | }); 156 | // Create the mock once called 157 | fetchClient = jest.fn((...args) => fetch.mockResponseOnce( 158 | JSON.stringify({ id: '123', name: 'joe' }), 159 | { status: 200, headers: { 'Content-Type': 'application/json' } } 160 | )(...args)); 161 | }; 162 | beforeEach(() => { 163 | setupFetchMock(); 164 | }); 165 | it('should be called when supplied by redux thunks', async () => { 166 | const thunk = executeFetch({ 167 | resource, id, opts, actionType: 'LOAD', 168 | }); 169 | const data = await thunk(dispatch, getState, { fetchClient }); 170 | expect(data).toEqual({ id: '123', name: 'joe' }); 171 | expect(fetch).toHaveBeenCalledWith( 172 | 'http://api.domain.com/users/123', 173 | { 174 | default: 'opt', method: 'GET', resource: 'opt', some: 'opt', 175 | } 176 | ); 177 | expect(dispatch).toHaveBeenCalledWith('waitAndDispatchFinishedThunk'); 178 | expect(fetchClient).toHaveBeenCalledTimes(1); 179 | expect(config.baseFetch).not.toHaveBeenCalled(); 180 | }); 181 | it('should not be called if not supplied and use baseFetch instead', async () => { 182 | const thunk = executeFetch({ 183 | resource, id, opts, actionType: 'LOAD', 184 | }); 185 | const data = await thunk(dispatch, getState); 186 | expect(data).toEqual({ id: '1234', name: 'bill' }); 187 | expect(fetch).toHaveBeenCalledWith( 188 | 'http://api.domain.com/users/123', 189 | { 190 | default: 'opt', method: 'GET', resource: 'opt', some: 'opt', 191 | } 192 | ); 193 | expect(fetchClient).not.toHaveBeenCalled(); 194 | expect(config.baseFetch).toHaveBeenCalledTimes(1); 195 | }); 196 | }); 197 | describe('composeFetch', () => { 198 | // Helpers and Mocks 199 | let fetchClient; 200 | const mockFetch = jest.fn((fetch) => fetch); 201 | const composeFetch = jest.fn((fetch) => mockFetch(fetch)); 202 | 203 | const setupFetchMock = () => { 204 | Object.assign(config, { 205 | // Create the mock once called 206 | baseFetch: jest.fn((...args) => fetch.mockResponseOnce( 207 | JSON.stringify({ id: '1234', name: 'bill' }), 208 | { status: 200, headers: { 'Content-Type': 'application/json' } } 209 | )(...args)), 210 | composeFetch, 211 | defaultOpts: { default: 'opt' }, 212 | resources: { 213 | users: { 214 | fetch: () => ({ 215 | url: 'http://api.domain.com/users/:id', 216 | opts: { 217 | resource: 'opt', 218 | }, 219 | }), 220 | }, 221 | }, 222 | }); 223 | // Create the mock once called 224 | fetchClient = jest.fn((...args) => fetch.mockResponseOnce( 225 | JSON.stringify({ id: '123', name: 'joe' }), 226 | { status: 200, headers: { 'Content-Type': 'application/json' } } 227 | )(...args)); 228 | }; 229 | 230 | beforeEach(() => { 231 | mockFetch.mockClear(); 232 | composeFetch.mockClear(); 233 | }); 234 | 235 | it('should compose with baseFetch config and call resulting fetch func', async () => { 236 | setupFetchMock(); 237 | const thunk = executeFetch({ 238 | resource, id, opts, actionType: 'LOAD', 239 | }); 240 | const data = await thunk(dispatch, getState); 241 | expect(data).toEqual({ id: '1234', name: 'bill' }); 242 | expect(fetch).toHaveBeenCalledWith( 243 | 'http://api.domain.com/users/123', 244 | { 245 | default: 'opt', method: 'GET', resource: 'opt', some: 'opt', 246 | } 247 | ); 248 | expect(dispatch).toHaveBeenCalledWith('waitAndDispatchFinishedThunk'); 249 | expect(config.baseFetch).toHaveBeenCalledTimes(1); 250 | expect(fetchClient).not.toHaveBeenCalled(); 251 | expect(composeFetch).toHaveBeenCalledWith(config.baseFetch); 252 | expect(mockFetch).toHaveBeenCalled(); 253 | }); 254 | it('should compose with fetchClient and call resulting fetch func', async () => { 255 | setupFetchMock(); 256 | 257 | const thunk = executeFetch({ 258 | resource, id, opts, actionType: 'LOAD', 259 | }); 260 | const data = await thunk(dispatch, getState, { fetchClient }); 261 | expect(data).toEqual({ id: '123', name: 'joe' }); 262 | expect(fetch).toHaveBeenCalledWith( 263 | 'http://api.domain.com/users/123', 264 | { 265 | default: 'opt', method: 'GET', resource: 'opt', some: 'opt', 266 | } 267 | ); 268 | expect(dispatch).toHaveBeenCalledWith('waitAndDispatchFinishedThunk'); 269 | expect(fetchClient).toHaveBeenCalledTimes(1); 270 | expect(config.baseFetch).not.toHaveBeenCalled(); 271 | expect(composeFetch).toHaveBeenCalledWith(fetchClient); 272 | expect(mockFetch).toHaveBeenCalled(); 273 | }); 274 | it('should not be called if not supplied and use baseFetch instead', async () => { 275 | Object.assign(config, { 276 | // Create the mock once called 277 | baseFetch: jest.fn((...args) => fetch.mockResponseOnce( 278 | JSON.stringify({ id: '1234', name: 'bill' }), 279 | { status: 200, headers: { 'Content-Type': 'application/json' } } 280 | )(...args)), 281 | composeFetch: (fetch) => fetch, 282 | defaultOpts: { default: 'opt' }, 283 | resources: { 284 | users: { 285 | fetch: () => ({ 286 | url: 'http://api.domain.com/users/:id', 287 | opts: { 288 | resource: 'opt', 289 | }, 290 | }), 291 | }, 292 | }, 293 | }); 294 | const thunk = executeFetch({ 295 | resource, id, opts, actionType: 'LOAD', 296 | }); 297 | const data = await thunk(dispatch, getState); 298 | expect(data).toEqual({ id: '1234', name: 'bill' }); 299 | expect(fetch).toHaveBeenCalledWith( 300 | 'http://api.domain.com/users/123', 301 | { 302 | default: 'opt', method: 'GET', resource: 'opt', some: 'opt', 303 | } 304 | ); 305 | expect(fetchClient).not.toHaveBeenCalled(); 306 | expect(config.baseFetch).toHaveBeenCalledTimes(1); 307 | expect(composeFetch).not.toHaveBeenCalled(); 308 | expect(mockFetch).not.toHaveBeenCalled(); 309 | }); 310 | }); 311 | }); 312 | -------------------------------------------------------------------------------- /__tests__/actions/crud.spec.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import { 18 | loadResource, 19 | loadCollection, 20 | createResource, 21 | updateResource, 22 | updateCollection, 23 | destroyResource, 24 | patchResource, 25 | } from '../../src/actions/crud'; 26 | 27 | jest.mock('../../src/selectors', () => ({ 28 | getResourceIsLoaded: jest.fn(), 29 | getResource: jest.fn(() => () => {}), 30 | resourceIsLoading: jest.fn(), 31 | getResourceLoadPromise: jest.fn(), 32 | getCollectionIsLoaded: jest.fn(), 33 | getCollection: jest.fn(() => () => []), 34 | collectionIsLoading: jest.fn(), 35 | getCollectionLoadPromise: jest.fn(), 36 | })); 37 | 38 | const mockFetchPromise = Promise.resolve('res'); 39 | jest.mock('../../src/actions/executeFetch', () => jest.fn(() => mockFetchPromise)); 40 | 41 | const executeFetch = require('../../src/actions/executeFetch'); 42 | 43 | const dispatch = jest.fn(); 44 | const getState = () => 'state'; 45 | const resource = 'users'; 46 | const id = '123'; 47 | const opts = { some: 'opt' }; 48 | 49 | describe('CRUD actions', () => { 50 | afterEach(() => { 51 | jest.clearAllMocks(); 52 | }); 53 | 54 | describe('loadResource', () => { 55 | it('should load a single resource if it is not loaded or loading', async () => { 56 | const thunk = loadResource({ resource, id, opts }); 57 | require('../../src/selectors').getResourceIsLoaded.mockImplementationOnce(() => () => false); // eslint-disable-line global-require 58 | require('../../src/selectors').resourceIsLoading.mockImplementationOnce(() => () => false); // eslint-disable-line global-require 59 | await thunk(dispatch, getState); 60 | expect(dispatch).toHaveBeenCalledWith(mockFetchPromise); 61 | expect(executeFetch).toHaveBeenCalledWith({ 62 | resource, id, opts, actionType: 'LOAD', 63 | }); 64 | }); 65 | 66 | it('should resolve with the cached resource if it is already loaded', async () => { 67 | const thunk = loadResource({ resource, id, opts }); 68 | require('../../src/selectors').getResourceIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 69 | await thunk(dispatch, getState); 70 | expect(dispatch).not.toHaveBeenCalled(); 71 | expect(executeFetch).not.toHaveBeenCalled(); 72 | }); 73 | 74 | it('should reject if the resource is loaded, but it loaded unsuccessfully', async () => { 75 | const error = new Error('load error'); 76 | try { 77 | const thunk = loadResource({ resource, id, opts }); 78 | require('../../src/selectors').getResourceIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 79 | require('../../src/selectors').getResource.mockImplementationOnce(() => () => error); // eslint-disable-line global-require 80 | await thunk(dispatch, getState); 81 | } catch (e) { 82 | expect(e).toBe(error); 83 | expect(dispatch).not.toHaveBeenCalled(); 84 | expect(executeFetch).not.toHaveBeenCalled(); 85 | } 86 | }); 87 | 88 | it('should return with the loading promise if it is already in progress', async () => { 89 | const thunk = loadResource({ resource, id, opts }); 90 | require('../../src/selectors').getResourceIsLoaded.mockImplementationOnce(() => () => false); // eslint-disable-line global-require 91 | require('../../src/selectors').resourceIsLoading.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 92 | require('../../src/selectors').getResourceLoadPromise.mockImplementationOnce(() => () => Promise.resolve()); // eslint-disable-line global-require 93 | await thunk(dispatch, getState); 94 | expect(dispatch).not.toHaveBeenCalled(); 95 | expect(executeFetch).not.toHaveBeenCalled(); 96 | }); 97 | 98 | it('should refetch the resource if the resource is loaded, but forceFetch is specified', async () => { 99 | const thunk = loadResource({ 100 | resource, id, opts, forceFetch: true, 101 | }); 102 | require('../../src/selectors').getResourceIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 103 | require('../../src/selectors').resourceIsLoading.mockImplementationOnce(() => () => false); // eslint-disable-line global-require 104 | await thunk(dispatch, getState); 105 | expect(dispatch).toHaveBeenCalledWith(mockFetchPromise); 106 | expect(executeFetch).toHaveBeenCalledWith({ 107 | resource, id, opts, actionType: 'LOAD', 108 | }); 109 | }); 110 | 111 | it('should refetch the resource if a fetch is in progess, but forceFetch is specified', async () => { 112 | const thunk = loadResource({ 113 | resource, id, opts, forceFetch: true, 114 | }); 115 | require('../../src/selectors').getResourceIsLoaded.mockImplementationOnce(() => () => false); // eslint-disable-line global-require 116 | require('../../src/selectors').resourceIsLoading.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 117 | await thunk(dispatch, getState); 118 | expect(dispatch).toHaveBeenCalledWith(mockFetchPromise); 119 | expect(executeFetch).toHaveBeenCalledWith({ 120 | resource, id, opts, actionType: 'LOAD', 121 | }); 122 | }); 123 | }); 124 | 125 | describe('loadCollection', () => { 126 | it('should load the collection if it is not loaded or loading', async () => { 127 | const thunk = loadCollection({ resource, opts }); 128 | require('../../src/selectors').getCollectionIsLoaded.mockImplementationOnce(() => () => false); // eslint-disable-line global-require 129 | require('../../src/selectors').collectionIsLoading.mockImplementationOnce(() => () => false); // eslint-disable-line global-require 130 | await thunk(dispatch, getState); 131 | expect(dispatch).toHaveBeenCalledWith(mockFetchPromise); 132 | expect(executeFetch).toHaveBeenCalledWith({ resource, opts, actionType: 'LOAD_COLLECTION' }); 133 | }); 134 | 135 | it('should not refetch the collection if it is already loaded', async () => { 136 | const thunk = loadCollection({ resource, opts }); 137 | require('../../src/selectors').getCollectionIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 138 | await thunk(dispatch, getState); 139 | expect(dispatch).not.toHaveBeenCalled(); 140 | expect(executeFetch).not.toHaveBeenCalled(); 141 | }); 142 | 143 | it('should reject if the collection is loaded, but it loaded unsuccessfully', async () => { 144 | const error = new Error('load error'); 145 | try { 146 | const thunk = loadCollection({ resource, id, opts }); 147 | require('../../src/selectors').getCollectionIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 148 | require('../../src/selectors').getCollection.mockImplementationOnce(() => () => error); // eslint-disable-line global-require 149 | await thunk(dispatch, getState); 150 | } catch (e) { 151 | expect(e).toBe(error); 152 | expect(dispatch).not.toHaveBeenCalled(); 153 | expect(executeFetch).not.toHaveBeenCalled(); 154 | } 155 | }); 156 | 157 | it('should not refetch the resource if a fetch is already in progress', async () => { 158 | const thunk = loadCollection({ resource, opts }); 159 | require('../../src/selectors').getCollectionIsLoaded.mockImplementationOnce(() => () => false); // eslint-disable-line global-require 160 | require('../../src/selectors').collectionIsLoading.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 161 | require('../../src/selectors').getCollectionLoadPromise.mockImplementationOnce(() => () => Promise.resolve()); // eslint-disable-line global-require 162 | await thunk(dispatch, getState); 163 | expect(dispatch).not.toHaveBeenCalled(); 164 | expect(executeFetch).not.toHaveBeenCalled(); 165 | }); 166 | 167 | it('should load the collection if the collection is loaded, but forceFetch is specified', async () => { 168 | const thunk = loadCollection({ resource, opts, forceFetch: true }); 169 | require('../../src/selectors').getCollectionIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 170 | require('../../src/selectors').collectionIsLoading.mockImplementationOnce(() => () => false); // eslint-disable-line global-require 171 | await thunk(dispatch, getState); 172 | expect(dispatch).toHaveBeenCalledWith(mockFetchPromise); 173 | expect(executeFetch).toHaveBeenCalledWith({ resource, opts, actionType: 'LOAD_COLLECTION' }); 174 | }); 175 | 176 | it('should refetch the collection if a fetch is in progess, but forceFetch is specified', async () => { 177 | const thunk = loadCollection({ 178 | resource, id, opts, forceFetch: true, 179 | }); 180 | require('../../src/selectors').getCollectionIsLoaded.mockImplementationOnce(() => () => false); // eslint-disable-line global-require 181 | require('../../src/selectors').collectionIsLoading.mockImplementationOnce(() => () => true); // eslint-disable-line global-require 182 | await thunk(dispatch, getState); 183 | expect(dispatch).toHaveBeenCalledWith(mockFetchPromise); 184 | expect(executeFetch).toHaveBeenCalledWith({ 185 | resource, id, opts, actionType: 'LOAD_COLLECTION', 186 | }); 187 | }); 188 | }); 189 | 190 | describe('createResource', () => { 191 | it('should create a new resource', async () => { 192 | const thunk = createResource({ resource, opts }); 193 | await thunk(dispatch, getState); 194 | expect(dispatch).toHaveBeenCalledWith(mockFetchPromise); 195 | expect(executeFetch).toHaveBeenCalledWith({ resource, opts, actionType: 'CREATE' }); 196 | }); 197 | }); 198 | 199 | describe('update', () => { 200 | it('should update an existing resource', async () => { 201 | const thunk = updateResource({ resource, id, opts }); 202 | await thunk(dispatch, getState); 203 | expect(dispatch).toHaveBeenCalledWith(mockFetchPromise); 204 | expect(executeFetch).toHaveBeenCalledWith({ 205 | resource, id, opts, actionType: 'UPDATE', 206 | }); 207 | }); 208 | }); 209 | 210 | describe('update collection', () => { 211 | it('should update an existing collection', async () => { 212 | const thunk = updateCollection({ resource, id, opts }); 213 | await thunk(dispatch, getState); 214 | expect(dispatch).toHaveBeenCalledWith(mockFetchPromise); 215 | expect(executeFetch).toHaveBeenCalledWith({ 216 | resource, id, opts, actionType: 'UPDATE_COLLECTION', 217 | }); 218 | }); 219 | }); 220 | 221 | describe('destroy', () => { 222 | it('should destroy an existing resource', async () => { 223 | const thunk = destroyResource({ resource, id, opts }); 224 | await thunk(dispatch, getState); 225 | expect(dispatch).toHaveBeenCalledWith(mockFetchPromise); 226 | expect(executeFetch).toHaveBeenCalledWith({ 227 | resource, id, opts, actionType: 'DESTROY', 228 | }); 229 | }); 230 | }); 231 | 232 | describe('patch', () => { 233 | it('should patch an existing resource', async () => { 234 | const thunk = patchResource({ resource, id, opts }); 235 | await thunk(dispatch, getState); 236 | expect(dispatch).toHaveBeenCalledWith(mockFetchPromise); 237 | expect(executeFetch).toHaveBeenCalledWith({ 238 | resource, id, opts, actionType: 'PATCH', 239 | }); 240 | }); 241 | }); 242 | }); 243 | -------------------------------------------------------------------------------- /src/reducer.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import { Map as iMap, List as iList, fromJS } from 'immutable'; 18 | 19 | import config from './config'; 20 | import * as iguazuRestTypes from './types'; 21 | import { 22 | getResourceIdHash, 23 | getCollectionIdHash, 24 | getQueryHash, 25 | } from './helpers/hash'; 26 | import { ARRAY_RESPONSE_ERROR } from './errors'; 27 | 28 | const { 29 | LOAD_STARTED, 30 | LOAD_COLLECTION_STARTED, 31 | CREATE_STARTED, 32 | UPDATE_STARTED, 33 | UPDATE_COLLECTION_STARTED, 34 | DESTROY_STARTED, 35 | PATCH_STARTED, 36 | LOAD_FINISHED, 37 | LOAD_ERROR, 38 | LOAD_COLLECTION_FINISHED, 39 | LOAD_COLLECTION_ERROR, 40 | CREATE_FINISHED, 41 | CREATE_ERROR, 42 | UPDATE_FINISHED, 43 | UPDATE_COLLECTION_FINISHED, 44 | UPDATE_COLLECTION_ERROR, 45 | UPDATE_ERROR, 46 | DESTROY_FINISHED, 47 | DESTROY_ERROR, 48 | CLEAR_RESOURCE, 49 | CLEAR_COLLECTION, 50 | RESET, 51 | PATCH_FINISHED, 52 | PATCH_ERROR, 53 | } = iguazuRestTypes; 54 | const iguazuRestTypesArray = Object.keys(iguazuRestTypes).map((key) => iguazuRestTypes[key]); 55 | 56 | function getIdKey(resource) { 57 | return config.resources[resource].idKey || 'id'; 58 | } 59 | 60 | export const initialResourceState = iMap({ 61 | items: iMap(), 62 | collections: iMap(), 63 | loading: iMap(), 64 | isCreating: false, 65 | updating: iMap(), 66 | destroying: iMap(), 67 | }); 68 | 69 | // eslint-disable-next-line complexity 70 | export function resourceReducer(state, action) { 71 | switch (action.type) { 72 | case LOAD_STARTED: { 73 | const { id, promise } = action; 74 | const idHash = getResourceIdHash(id); 75 | return state.update('loading', (map) => map.set(idHash, promise)); 76 | } 77 | 78 | case LOAD_COLLECTION_STARTED: { 79 | const { id, opts, promise } = action; 80 | const collectionIdHash = getCollectionIdHash(id); 81 | const queryHash = getQueryHash(opts); 82 | return state.update('loading', (map) => map.setIn([collectionIdHash, queryHash], promise)); 83 | } 84 | 85 | case CREATE_STARTED: { 86 | return state.set('isCreating', true); 87 | } 88 | 89 | case UPDATE_STARTED: { 90 | const { id, promise } = action; 91 | const idHash = getResourceIdHash(id); 92 | return state.update('updating', (map) => map.set(idHash, promise)); 93 | } 94 | 95 | case UPDATE_COLLECTION_STARTED: { 96 | const { id, opts, promise } = action; 97 | const collectionIdHash = getCollectionIdHash(id); 98 | const queryHash = getQueryHash(opts); 99 | return state.update('updating', (map) => map.setIn([collectionIdHash, queryHash], promise)); 100 | } 101 | 102 | case DESTROY_STARTED: { 103 | const { id, promise } = action; 104 | const idHash = getResourceIdHash(id); 105 | return state.update('destroying', (map) => map.set(idHash, promise)); 106 | } 107 | 108 | case PATCH_STARTED: { 109 | const { id, promise } = action; 110 | const idHash = getResourceIdHash(id); 111 | return state.update('updating', (map) => map.set(idHash, promise)); 112 | } 113 | 114 | case LOAD_FINISHED: { 115 | const { id, data } = action; 116 | const idHash = getResourceIdHash(id); 117 | return state.withMutations((resourceState) => (Array.isArray(data) 118 | ? resourceState 119 | .update('loading', (map) => map.delete(idHash)) 120 | .setIn(['error', idHash], new Error(ARRAY_RESPONSE_ERROR)) 121 | : resourceState 122 | .update('loading', (map) => map.delete(idHash)) 123 | .update('items', (map) => map.set(idHash, iMap(data))) 124 | .deleteIn(['error', idHash])) 125 | ); 126 | } 127 | 128 | case CLEAR_RESOURCE: { 129 | const { id } = action; 130 | const idHash = getResourceIdHash(id); 131 | return state.withMutations((resourceState) => { 132 | const withCollection = resourceState 133 | .get('collections', iList()) 134 | .toIndexedSeq() 135 | .flatMap((eachCollection) => eachCollection.toIndexedSeq()) 136 | .flatMap((eachRelatedQueryHash) => eachRelatedQueryHash.toIndexedSeq()) 137 | .flatMap((eachRelatedResourceCollection) => eachRelatedResourceCollection.toIndexedSeq()) 138 | .contains(idHash); 139 | 140 | if (withCollection) { 141 | return resourceState; 142 | } 143 | 144 | return resourceState 145 | .update('loading', (map) => map.delete(idHash)) 146 | .update('items', (map) => map.delete(idHash)) 147 | .deleteIn(['error', idHash]); 148 | } 149 | ); 150 | } 151 | 152 | case LOAD_ERROR: { 153 | const { id, data } = action; 154 | const idHash = getResourceIdHash(id); 155 | return state.withMutations((resourceState) => resourceState 156 | .update('loading', (map) => map.delete(idHash)) 157 | .setIn(['error', idHash], data) 158 | ); 159 | } 160 | 161 | case LOAD_COLLECTION_FINISHED: { 162 | const { 163 | id, resource: resourceType, data, opts, 164 | } = action; 165 | const collectionIdHash = getCollectionIdHash(id); 166 | const queryHash = getQueryHash(opts); 167 | const idKey = getIdKey(resourceType); 168 | const resourceMap = Array.isArray(data) 169 | ? data.reduce((map, resource) => { 170 | const resourceIdHash = getResourceIdHash(resource[idKey]); 171 | return Object.assign(map, { [resourceIdHash]: resource }); 172 | }, {}) : {}; 173 | const associatedIds = Object.keys(resourceMap); 174 | return state.withMutations((resourceState) => resourceState 175 | .deleteIn(['loading', collectionIdHash, queryHash]) 176 | .update('loading', (loading) => (loading.get(collectionIdHash, iMap()).isEmpty() ? loading.delete(collectionIdHash) : loading)) 177 | .mergeIn(['items'], fromJS(resourceMap)) 178 | .setIn( 179 | ['collections', collectionIdHash, queryHash], 180 | iMap({ associatedIds: iList(associatedIds) }) 181 | ) 182 | ); 183 | } 184 | 185 | case UPDATE_COLLECTION_FINISHED: { 186 | const { 187 | id, resource: resourceType, data, opts, 188 | } = action; 189 | const collectionIdHash = getCollectionIdHash(id); 190 | const queryHash = getQueryHash(opts); 191 | const idKey = getIdKey(resourceType); 192 | const resourceMap = Array.isArray(data) 193 | ? data.reduce((map, resource) => { 194 | const resourceIdHash = getResourceIdHash(resource[idKey]); 195 | return Object.assign(map, { [resourceIdHash]: resource }); 196 | }, {}) : {}; 197 | return state.withMutations((resourceState) => resourceState 198 | .deleteIn(['updating', collectionIdHash, queryHash]) 199 | .update('updating', (updating) => (updating.get(collectionIdHash, iMap()).isEmpty() ? updating.delete(collectionIdHash) : updating)) 200 | .mergeIn(['items'], fromJS(resourceMap)) 201 | ); 202 | } 203 | 204 | case CLEAR_COLLECTION: { 205 | const { id, opts } = action; 206 | const collectionIdHash = getCollectionIdHash(id); 207 | const queryHash = getQueryHash(opts); 208 | return state.withMutations((resourceState) => { 209 | const collections = resourceState.get('collections', iMap()); 210 | const myCollection = collections.getIn([collectionIdHash, queryHash, 'associatedIds'], iList()); 211 | const combinedIds = collections.removeIn([collectionIdHash, queryHash]) 212 | .toIndexedSeq() 213 | .flatMap((eachCollection) => eachCollection.toIndexedSeq()) 214 | .flatMap((eachRelatedQueryHash) => eachRelatedQueryHash.toIndexedSeq()) 215 | .flatMap((eachRelatedResourceCollection) => eachRelatedResourceCollection.toIndexedSeq()); 216 | 217 | const toDelete = myCollection 218 | .filterNot((associatedId) => combinedIds.contains(associatedId)); 219 | 220 | return ( 221 | toDelete 222 | .reduce((newState, associatedId) => newState.deleteIn(['items', associatedId]), resourceState) 223 | .deleteIn(['error', collectionIdHash, queryHash]) 224 | .deleteIn(['loading', collectionIdHash, queryHash]) 225 | .deleteIn(['collections', collectionIdHash, queryHash]) 226 | ); 227 | }); 228 | } 229 | 230 | case LOAD_COLLECTION_ERROR: { 231 | const { id, data, opts } = action; 232 | const collectionIdHash = getCollectionIdHash(id); 233 | const queryHash = getQueryHash(opts); 234 | return state.withMutations((resourceState) => resourceState 235 | .deleteIn(['loading', collectionIdHash, queryHash]) 236 | .update('loading', (map) => (map.get(collectionIdHash, iMap()).isEmpty() ? map.delete(collectionIdHash) : map)) 237 | .setIn(['collections', collectionIdHash, queryHash, 'error'], data) 238 | ); 239 | } 240 | 241 | case UPDATE_COLLECTION_ERROR: { 242 | const { id, opts } = action; 243 | const collectionIdHash = getCollectionIdHash(id); 244 | const queryHash = getQueryHash(opts); 245 | return state.withMutations((resourceState) => resourceState 246 | .deleteIn(['updating', collectionIdHash, queryHash]) 247 | .update('updating', (map) => (map.get(collectionIdHash, iMap()).isEmpty() ? map.delete(collectionIdHash) : map)) 248 | ); 249 | } 250 | 251 | case CREATE_FINISHED: { 252 | const { resource, data } = action; 253 | const idKey = getIdKey(resource); 254 | return state.withMutations((resourceState) => resourceState 255 | .set('isCreating', false) 256 | .update('items', (map) => map.set(getResourceIdHash(data[idKey]), fromJS(data))) 257 | .update('collections', (map) => map.clear()) 258 | ); 259 | } 260 | 261 | case CREATE_ERROR: { 262 | return state.withMutations((resourceState) => resourceState 263 | .set('isCreating', false) 264 | ); 265 | } 266 | 267 | case UPDATE_FINISHED: { 268 | const { id, data } = action; 269 | const idHash = getResourceIdHash(id); 270 | return state.withMutations((resourceState) => resourceState 271 | .update('updating', (map) => map.delete(idHash)) 272 | .update('items', (map) => map.set(idHash, fromJS(data))) 273 | ); 274 | } 275 | 276 | case UPDATE_ERROR: { 277 | const { id } = action; 278 | const idHash = getResourceIdHash(id); 279 | return state.withMutations((resourceState) => resourceState 280 | .update('updating', (map) => map.delete(idHash)) 281 | ); 282 | } 283 | 284 | case DESTROY_FINISHED: { 285 | const { id } = action; 286 | const idHash = getResourceIdHash(id); 287 | return state.withMutations((resourceState) => resourceState 288 | .update('destroying', (map) => map.delete(idHash)) 289 | .update('items', (map) => map.delete(idHash)) 290 | .update('collections', (idMap) => idMap.map((queryMap) => queryMap.map((m) => m.update('associatedIds', (ids) => (ids.indexOf(idHash) !== -1 ? ids.delete(ids.indexOf(idHash)) : ids) 291 | )))) 292 | ); 293 | } 294 | 295 | case DESTROY_ERROR: { 296 | const { id } = action; 297 | const idHash = getResourceIdHash(id); 298 | return state.withMutations((resourceState) => resourceState 299 | .update('destroying', (map) => map.delete(idHash)) 300 | ); 301 | } 302 | 303 | case PATCH_FINISHED: { 304 | const { id, data } = action; 305 | const idHash = getResourceIdHash(id); 306 | return state.withMutations((resourceState) => resourceState 307 | .update('updating', (map) => map.delete(idHash)) 308 | .update('items', (map) => map.set(idHash, fromJS(data))) 309 | ); 310 | } 311 | 312 | case PATCH_ERROR: { 313 | const { id } = action; 314 | const idHash = getResourceIdHash(id); 315 | return state.withMutations((resourceState) => resourceState 316 | .update('updating', (map) => map.delete(idHash)) 317 | ); 318 | } 319 | 320 | default: 321 | return state; 322 | } 323 | } 324 | 325 | export default function rootReducer(state = iMap(), action) { 326 | if (action.type === RESET) { 327 | return iMap(); 328 | } if (iguazuRestTypesArray.includes(action.type)) { 329 | return state.update( 330 | action.resource, 331 | initialResourceState, 332 | (resourceState) => resourceReducer(resourceState, action) 333 | ); 334 | } 335 | 336 | return state; 337 | } 338 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > ## **NOTICE:** Iguazu is no longer maintained. If you're looking for a data fetching solution for your React application, consider [Fetchye](https://github.com/americanexpress/fetchye). It is more performant and has a more intuitive API. If you know fetch, you know Fetchye. 2 | 3 |

4 | Iguazu Rest - One Amex 5 |

6 | 7 | [![npm](https://img.shields.io/npm/v/iguazu-rest)](https://www.npmjs.com/package/iguazu-rest) 8 | ![Health Check](https://github.com/americanexpress/iguazu-rest/workflows/Health%20Check/badge.svg) 9 | 10 | > Iguazu REST is a plugin for the [Iguazu](https://github.com/americanexpress/iguazu) 11 | > ecosystem that allows for pre-built async calls for REST with smart caching in Redux. 12 | > If your API uses RESTful patterns, this library will save you time to perform 13 | > CRUD actions. If your API does not follow REST patterns, check out [Iguazu RPC](https://github.com/americanexpress/iguazu-rpc). 14 | 15 | ## 👩‍💻 Hiring 👨‍💻 16 | 17 | Want to get paid for your contributions to `iguazu-rest`? 18 | > Send your resume to oneamex.careers@aexp.com 19 | 20 | ## 📖 Table of Contents 21 | 22 | * [Features](#-features) 23 | * [Usage](#-usage) 24 | * [API](#-api) 25 | * [Contributing](#-contributing) 26 | 27 | ## ✨ Features 28 | 29 | * Plugs into [Iguazu](https://github.com/americanexpress/iguazu) 30 | * Easy dispatchable actions for create, read, update, destroy to call a REST API 31 | * Caching requests based on the RESTful action 32 | * Seamless integration in Redux 33 | 34 | ## 🤹‍ Usage 35 | 36 | ### Installation 37 | 38 | ```bash 39 | npm install --save iguazu-rest 40 | ``` 41 | 42 | ### Config 43 | Iguazu REST uses a config object that allows you to register resources and provide default and override behavior. 44 | 45 | ```javascript 46 | import { createStore, combineReducers, applyMiddleware } from 'redux'; 47 | import { configureIguazuREST, resourcesReducer } from 'iguazu-rest'; 48 | import thunk from 'redux-thunk'; 49 | 50 | configureIguazuREST({ 51 | // the resources you want cached 52 | resources: { 53 | // this key will be used in actions 54 | users: { 55 | // returns the url and opts that should be passed to fetch 56 | fetch: () => ({ 57 | // the resource id should always use ':id', nested ids should be more specific 58 | url: `${process.env.HOST_URL}/users/:id`, 59 | // opts that will be sent on every request for this resource 60 | opts: { 61 | credentials: 'include', 62 | }, 63 | }), 64 | // optionally override the resources id key, defaults to 'id' 65 | // this is only used to extract the id after a create 66 | // or to get the ids of the resources in a collection 67 | idKey: 'userId', 68 | // optionally massage the data to be more RESTful, 69 | // collections need to be lists, resources need to be objects 70 | transformData: (data, { id, actionType, state }) => massageDataToBeRESTful(data), 71 | }, 72 | }, 73 | // opts that will be sent along with every resource request 74 | defaultOpts: { 75 | headers: { 76 | Accept: 'application/json', 77 | 'Content-Type': 'application/json', 78 | }, 79 | }, 80 | // extend fetch with some added functionality 81 | baseFetch: fetchWith6sTimeout, 82 | // override state location, defaults to state.resources 83 | getToState: (state) => state.data.resources, 84 | }); 85 | 86 | const store = createStore( 87 | combineReducers({ 88 | resources: resourcesReducer, 89 | }), 90 | applyMiddleware(thunk) 91 | ); 92 | ``` 93 | 94 | ### Advanced Config 95 | 96 | You may also supply a custom `fetch` client to iguazu-rest using Redux Thunk. 97 | This will *override* any `baseFetch` configuration in Iguazu REST with the 98 | `thunk` supplied fetch client. (See [Thunk withExtraArgument 99 | docs](https://github.com/reduxjs/redux-thunk#injecting-a-custom-argument)) 100 | 101 | This approach allows for the client and the server to specify different `fetch` 102 | implementations. For example, the server needs to support cookies inside a 103 | server-side fetch versus the client-side which works with cookies by default. 104 | Thunk-provided `fetchClient` overrides `baseFetch` as the concerns of the 105 | environment are more important such as providing cookie support on the server or 106 | enforcing request timeouts. 107 | 108 | To retain the ability to apply additional fetch functionality with a thunk-provided 109 | `fetchClient` you may also extend the behavior by providing a `composeFetch` 110 | function in the configuration that returns a composed fetch function. 111 | 112 | ```javascript 113 | import { createStore, combineReducers, applyMiddleware } from 'redux'; 114 | import { configureIguazuREST, resourcesReducer } from 'iguazu-rest'; 115 | import thunk from 'redux-thunk'; 116 | 117 | configureIguazuREST({ 118 | // Assume configuration from above... 119 | 120 | // Overriden by thunk.withExtraArgument below 121 | baseFetch: fetchWith6sTimeout, 122 | 123 | // Restored functionality with composition 124 | composeFetch: (customFetch) => composeFetchWith6sTimeout(customFetch), 125 | }); 126 | 127 | /* Contrived custom fetch client */ 128 | const customFetchClient = (...args) => fetch(...args); 129 | 130 | const store = createStore( 131 | combineReducers({ 132 | resources: resourcesReducer, 133 | }), 134 | applyMiddleware(thunk.withExtraArgument({ 135 | fetchClient: customFetchClient, 136 | })) 137 | ); 138 | ``` 139 | 140 | #### Resource Fetch Function 141 | In an ideal world, your REST API follows all the [right patterns and best practices](http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#useful-post-responses). If that is the case your fetch function can return a simple url and iguazu-rest will fill in the parameters based on the id you pass to the action. Not all of us live in an ideal world though and sometimes your boss tells you that you need to support some API endpoints that cannot be made RESTful because it's too much effort. Maybe you need to put the resource ID in the header instead of the URL or you need to make a POST to load a resource. In that case you can use some of the parameters passed to the fetch function to get creative. 142 | 143 | ##### Arguments 144 | * [`id`] \(String, Object, or Undefined): The id that was passed into the action. May be a string if only one id needs to be specified, an object if multiple ids need to be specified (nested urls), or undefined if no ids need to be specified (simple collection). Useful if your unique identifiers are not confined to the url. If you are using an object, the resource id key should always be named 'id' and the nested id keys should be more specific. 145 | * [`actionType`] \(String): The type of CRUD action. Will be one of `LOAD`, `LOAD_COLLECTION`, `CREATE`, `UPDATE`, `DESTROY`. 146 | * [`state`] \(Object): The redux state. Useful if you need to use some config held in state. Keep in mind that you should not use this to grab any unique identifiers as the id argument is what is used to cache. 147 | 148 | #### Collections 149 | 150 | To use the functions that operate on collections, your API and config needs to meet some basic requirements: 151 | 152 | * The URL specified on the `fetch` config should return the full collection when the `/:id` is omitted. 153 | * URLs can have optional path parameters by including `?`, such as `${process.env.HOST_URL}/users/:userId?/books`. 154 | * The API must return an array of resource objects. If it returns an object (common in paged APIs), you can use the `transformData` config function to return the array field of the object instead. 155 | * Each object in the array must have a unique ID field, normally named `id`. If it is not named `id`, then the field name must be set in the `idKey` prop on the resource config. Iguazu will throw an error on successful network responses if it cannot find a unique ID for each item in the array. 156 | 157 | ### Reducer 158 | ```javascript 159 | import { resourcesReducer } from 'iguazu-rest'; 160 | import { combineReducers, createStore } from 'redux'; 161 | 162 | const reducer = combineReducers({ 163 | resources: resourcesReducer, 164 | // other reducers 165 | }); 166 | 167 | const store = createStore(reducer); 168 | ``` 169 | ### Actions 170 | All iguazu-rest actions accept the same type of object as their single argument. The object can have the following properties: 171 | 172 | * [`resource`] \(String): The name of the resource type, must match the key in resources config. 173 | * [`id`] \(String, Object, or Undefined): The id or ids to be populated in the REST call. May be a string if only one id needs to be specified, an object if multiple ids need to be specified (nested urls), or undefined if no ids need to be specified (simple collection). If you are using an object, the resource id key should always be named 'id' and the nested id keys should be more specific. 174 | * [`opts`] \(Object or Undefined): fetch opts to be sent along with the REST call 175 | * [`forceFetch`] \(Boolean or Undefined): forces the REST call to be made regardless of whether the resource or collection is loaded or not. Only applies to queryResource, queryCollection, loadCollection, and queryCollection. 176 | 177 | ## 🎛️ API 178 | 179 | ### Iguazu Actions 180 | #### `queryResource({ resource, id, opts, forceFetch })` 181 | #### `queryCollection({ resource, id, opts, forceFetch })` 182 | 183 | These actions return an object following the iguazu pattern `{ data, status, promise}`. 184 | 185 | **Example:** 186 | 187 | ```jsx 188 | // Author.jsx 189 | import { connectAsync } from 'iguazu'; 190 | import { queryResource } from 'iguazu-rest'; 191 | import BookList from './BookList'; 192 | 193 | const Author = ({ id, author: { name, bio } }) => ( 194 |
195 |
{name}
196 |
{bio}
197 | 198 |
199 | ); 200 | 201 | function loadDataAsProps({ store: { dispatch }, ownProps: { id } }) { 202 | return { 203 | author: () => dispatch(queryResource({ resource: 'author', id })), 204 | }; 205 | } 206 | 207 | export default connectAsync({ loadDataAsProps })(Author); 208 | ``` 209 | 210 | ```jsx 211 | // BookList.jsx 212 | import { connectAsync } from 'iguazu'; 213 | import { queryCollection } from 'iguazu-rest'; 214 | 215 | const BookList = ({ books }) => ( 216 |
217 | {books.map((book) => )} 218 |
219 | ); 220 | 221 | function loadDataAsProps({ store: { dispatch }, ownProps: { authorId } }) { 222 | return { 223 | books: () => dispatch(queryCollection({ resource: 'book', id: { authorId } })), 224 | }; 225 | } 226 | 227 | export default connectAsync({ loadDataAsProps })(BookList); 228 | ``` 229 | 230 | ### CRUD Actions 231 | #### `loadResource({ resource, id, opts, forceFetch })` 232 | #### `loadCollection({ resource, id, opts, forceFetch })` 233 | #### `createResource({ resource, id, opts })` 234 | #### `updateResource({ resource, id, opts })` 235 | #### `updateCollection({ resource, id, opts })` 236 | #### `destroyResource({ resource, id, opts })` 237 | #### `patchResource({ resource, id, opts })` 238 | 239 | These actions return a promise that resolves with the fetched data on successful requests and reject with an error on unsuccessful requests. The error also contains the status and the body if you need to inspect those. 240 | 241 | ### Selectors 242 | #### `getResource({ resource, id })(state)` 243 | #### `getResourceIsLoaded({ resource, id })(state)` 244 | #### `getCollection({ resource, id, opts })(state)` 245 | #### `getCollectionIsLoaded({ resource, id, opts })(state)` 246 | 247 | ### Cleaning Actions 248 | #### `clearResource({ resource, id, opts })` 249 | #### `clearCollection({ resource, id, opts })` 250 | 251 | These actions allow you to remove the associated data to a resource or collection from the state tree without performing any operation on the remote resource itself. 252 | * resources associated to a collection will only be removed if no other collection is using that same resource 253 | * individual resources will only be removed if they are not associated to any collection 254 | 255 | ### Query opts 256 | iguazu-rest allows you to specify your query parameters as part of the opts passed to fetch. If they are used to filter a collection, make sure they are passed in this way instead of adding them directly to the url because it is necessary for proper caching. All of the resources get normalized, so iguazu-rest needs to a way to cache which resources came back for a set of query parameters. 257 | 258 | ```jsx 259 | // Articles.jsx 260 | import { connectAsync } from 'iguazu'; 261 | import { queryCollection } from 'iguazu-rest'; 262 | 263 | const Articles = ({ articles }) => ( 264 |
265 | {articles.map((article) =>
)} 266 |
267 | ); 268 | 269 | function loadDataAsProps({ store: { dispatch } }) { 270 | return { 271 | articles: () => dispatch(queryCollection({ 272 | resource: 'articles', 273 | opts: { 274 | query: { limit: 10, sortBy: 'title' }, 275 | }, 276 | })), 277 | }; 278 | } 279 | 280 | export default connectAsync({ loadDataAsProps })(Articles); 281 | ``` 282 | 283 | ### Method Opts 284 | 285 | Some REST APIs support bulk updates as opposed to individual resource updates. There are many thoughts on this matter but they generally suggest using a POST or a PUT for this type of CRUD action. For iguazu-rest, we take the opinion that by default, updating a collection should be a POST but provide the option to override the method. 286 | 287 | ```jsx 288 | // Articles.jsx 289 | import React, { Component, Fragment } from 'react'; 290 | import { connectAsync } from 'iguazu'; 291 | import { updateCollection } from 'iguazu-rest'; 292 | 293 | class MyUpdatingComponent extends Component { 294 | constructor(props) { 295 | super(props); 296 | this.state = { articles: [{ id: '1', body: 'article 1' }, { id: '2', body: 'article 2' }] }; 297 | } 298 | 299 | handleClick = () => { 300 | const { updateManyArticles } = this.props; 301 | const { articles } = this.state; 302 | return updateManyArticles(articles) 303 | .then((updatedArticles) => { 304 | this.setState({ articles: updatedArticles }); 305 | }); 306 | }; 307 | 308 | render() { 309 | const { isLoading, loadedWithErrors, myData } = this.props; 310 | const { articles } = this.state; 311 | 312 | return ( 313 | 314 | 315 |
{articles.map((article) =>
)}
316 |
317 | ); 318 | } 319 | } 320 | 321 | function mapDispatchToProps(dispatch) { 322 | return { 323 | updateManyArticles: (articles) => dispatch(updateCollection({ 324 | resource: 'articles', 325 | opts: { 326 | method: 'PUT', 327 | body: articles, 328 | }, 329 | })), 330 | }; 331 | } 332 | 333 | export default connect(null, mapDispatchToProps)(Articles); 334 | ``` 335 | 336 | ## 🏆 Contributing 337 | 338 | We welcome Your interest in the American Express Open Source Community on Github. 339 | Any Contributor to any Open Source Project managed by the American Express Open 340 | Source Community must accept and sign an Agreement indicating agreement to the 341 | terms below. Except for the rights granted in this Agreement to American Express 342 | and to recipients of software distributed by American Express, You reserve all 343 | right, title, and interest, if any, in and to Your Contributions. Please [fill 344 | out the Agreement](https://cla-assistant.io/americanexpress/iguazu-rest). 345 | 346 | Please feel free to open pull requests and see [CONTRIBUTING.md](./CONTRIBUTING.md) to learn how to get started contributing. 347 | 348 | ## 🗝️ License 349 | 350 | Any contributions made under this project will be governed by the [Apache License 351 | 2.0](https://github.com/americanexpress/iguazu-rest/blob/main/LICENSE.txt). 352 | 353 | ## 🗣️ Code of Conduct 354 | 355 | This project adheres to the [American Express Community Guidelines](./CODE_OF_CONDUCT.md). 356 | By participating, you are expected to honor these guidelines. 357 | -------------------------------------------------------------------------------- /__tests__/reducer.spec.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 American Express Travel Related Services Company, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 | * or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | import { fromJS, Map as iMap, List as iList } from 'immutable'; 18 | 19 | import { 20 | getResourceIdHash, 21 | getCollectionIdHash, 22 | getQueryHash, 23 | } from '../src/helpers/hash'; 24 | import { 25 | LOAD_STARTED, 26 | LOAD_COLLECTION_STARTED, 27 | CREATE_STARTED, 28 | UPDATE_STARTED, 29 | UPDATE_COLLECTION_STARTED, 30 | DESTROY_STARTED, 31 | PATCH_STARTED, 32 | LOAD_FINISHED, 33 | LOAD_ERROR, 34 | LOAD_COLLECTION_FINISHED, 35 | LOAD_COLLECTION_ERROR, 36 | CREATE_FINISHED, 37 | CREATE_ERROR, 38 | UPDATE_FINISHED, 39 | UPDATE_ERROR, 40 | UPDATE_COLLECTION_FINISHED, 41 | UPDATE_COLLECTION_ERROR, 42 | DESTROY_FINISHED, 43 | DESTROY_ERROR, 44 | RESET, 45 | CLEAR_RESOURCE, 46 | CLEAR_COLLECTION, 47 | PATCH_FINISHED, 48 | PATCH_ERROR, 49 | } from '../src/types'; 50 | 51 | import resourcesReducer, { 52 | initialResourceState, 53 | resourceReducer, 54 | } from '../src/reducer'; 55 | 56 | jest.mock('../src/config', () => ({ 57 | resources: { users: {} }, 58 | })); 59 | 60 | const id = { id: '123' }; 61 | 62 | describe('reducer', () => { 63 | describe('resourceReducer', () => { 64 | it('should handle LOAD_STARTED action', () => { 65 | const promise = Promise.resolve(); 66 | const action = { 67 | type: LOAD_STARTED, 68 | id, 69 | promise, 70 | }; 71 | const newState = resourceReducer(initialResourceState, action); 72 | expect(newState.getIn(['loading', getResourceIdHash(id)])).toEqual(promise); 73 | }); 74 | 75 | it('should handle LOAD_COLLECTION_STARTED action', () => { 76 | const promise = Promise.resolve(); 77 | const collectionIdHash = getCollectionIdHash(); 78 | const queryHash = getQueryHash(); 79 | const action = { 80 | type: LOAD_COLLECTION_STARTED, 81 | promise, 82 | }; 83 | const newState = resourceReducer(initialResourceState, action); 84 | expect(newState.getIn(['loading', collectionIdHash, queryHash])).toEqual(promise); 85 | }); 86 | 87 | it('should handle CREATE_STARTED action', () => { 88 | const promise = Promise.resolve(); 89 | const action = { 90 | type: CREATE_STARTED, 91 | promise, 92 | }; 93 | const newState = resourceReducer(initialResourceState, action); 94 | expect(newState.get('isCreating')).toEqual(true); 95 | }); 96 | 97 | it('should handle UPDATE_STARTED action', () => { 98 | const promise = Promise.resolve(); 99 | const action = { 100 | type: UPDATE_STARTED, 101 | id, 102 | promise, 103 | }; 104 | const newState = resourceReducer(initialResourceState, action); 105 | expect(newState.getIn(['updating', getResourceIdHash(id)])).toEqual(promise); 106 | }); 107 | 108 | it('should handle UPDATE_COLLECTION_STARTED action', () => { 109 | const promise = Promise.resolve(); 110 | const collectionIdHash = getCollectionIdHash(); 111 | const queryHash = getQueryHash(); 112 | const action = { 113 | type: UPDATE_COLLECTION_STARTED, 114 | promise, 115 | }; 116 | const newState = resourceReducer(initialResourceState, action); 117 | expect(newState.getIn(['updating', collectionIdHash, queryHash])).toEqual(promise); 118 | }); 119 | 120 | it('should handle DESTROY_STARTED action', () => { 121 | const promise = Promise.resolve(); 122 | const action = { 123 | type: DESTROY_STARTED, 124 | id, 125 | promise, 126 | }; 127 | const newState = resourceReducer(initialResourceState, action); 128 | expect(newState.getIn(['destroying', getResourceIdHash(id)])).toEqual(promise); 129 | }); 130 | 131 | it('should handle PATCH_STARTED action', () => { 132 | const promise = Promise.resolve(); 133 | const action = { 134 | type: PATCH_STARTED, 135 | id, 136 | promise, 137 | }; 138 | const newState = resourceReducer(initialResourceState, action); 139 | expect(newState.getIn(['updating', getResourceIdHash(id)])).toEqual(promise); 140 | }); 141 | 142 | it('should handle LOAD_FINISHED action', () => { 143 | const promise = Promise.resolve(); 144 | const data = { id, some: 'property' }; 145 | const idHash = getResourceIdHash(id); 146 | const action = { 147 | type: LOAD_FINISHED, 148 | id, 149 | data, 150 | }; 151 | const initialState = initialResourceState.setIn(['loading', idHash], promise); 152 | const newState = resourceReducer(initialState, action); 153 | expect(newState.getIn(['loading', idHash])).toBeUndefined(); 154 | expect(newState.getIn(['items', idHash]).toJS()).toEqual(data); 155 | }); 156 | 157 | it('should handle CLEAR_RESOURCE action', () => { 158 | const otherId = { id: 456 }; 159 | const idHash = getResourceIdHash(id); 160 | const otherIdHash = getResourceIdHash(otherId); 161 | const collectionHash = getCollectionIdHash({}); 162 | const queryHash = getQueryHash({ param: 'key' }); 163 | 164 | const action = { 165 | type: CLEAR_RESOURCE, 166 | id, 167 | }; 168 | const otherAction = { 169 | type: CLEAR_RESOURCE, 170 | id: otherId, 171 | }; 172 | 173 | const initialState = initialResourceState 174 | .setIn(['items', idHash], iMap({ prop: 'value' })) 175 | .setIn(['items', otherIdHash], iMap({ prop: 'other value' })) 176 | .setIn( 177 | ['collections', collectionHash, queryHash], 178 | iMap({ associatedIds: iList([otherIdHash]) }) 179 | ); 180 | 181 | const newState = resourceReducer(initialState, action); 182 | expect(newState.getIn(['loading', idHash])).toBeUndefined(); 183 | expect(newState.getIn(['items', idHash])).toBeUndefined(); 184 | expect(newState.getIn(['error', idHash])).toBeUndefined(); 185 | 186 | const otherState = resourceReducer(initialState, otherAction); 187 | expect(otherState.getIn(['loading', otherIdHash])).toBeUndefined(); 188 | expect(otherState.getIn(['items', otherIdHash]).toJS()).toEqual({ prop: 'other value' }); 189 | expect(otherState.getIn(['error', otherIdHash])).toBeUndefined(); 190 | }); 191 | 192 | it('should handle storing resource by id object', () => { 193 | const promise = Promise.resolve(); 194 | const idObj = { id: '123', param1: 'a', param2: 'b' }; 195 | const data = { id: '123', some: 'property' }; 196 | const idObjHash = getResourceIdHash(idObj); 197 | const action = { 198 | type: LOAD_FINISHED, 199 | id: idObj, 200 | data, 201 | }; 202 | const initialState = initialResourceState.setIn(['loading', idObjHash], promise); 203 | const newState = resourceReducer(initialState, action); 204 | expect(newState.getIn(['loading', idObjHash])).toBeUndefined(); 205 | expect(newState.getIn(['items', idObjHash]).toJS()).toEqual(data); 206 | }); 207 | 208 | it('should set in error if data of incorrect array type passed to LOAD_FINISHED', () => { 209 | const promise = Promise.resolve(); 210 | const idObj = { id: '123', param1: 'a', param2: 'b' }; 211 | const data = [{ id: '123', some: 'property' }]; 212 | const idObjHash = getResourceIdHash(idObj); 213 | const action = { 214 | type: LOAD_FINISHED, 215 | id: idObj, 216 | data, 217 | }; 218 | const initialState = initialResourceState.setIn(['loading', idObjHash], promise); 219 | const newState = resourceReducer(initialState, action); 220 | expect(newState.getIn(['loading', idObjHash])).toBeUndefined(); 221 | expect(newState.getIn(['items', idObjHash])).toBeUndefined(); 222 | expect(newState.getIn(['error', idObjHash])).toEqual(new Error('Resource call must return an object, not an array')); 223 | }); 224 | 225 | it('should reset error on subsequent LOAD_FINISHED success', () => { 226 | const promise = Promise.resolve(); 227 | const error = new Error('load error'); 228 | const data = { id, some: 'property' }; 229 | const idHash = getResourceIdHash(id); 230 | const action = { 231 | type: LOAD_FINISHED, 232 | id, 233 | data, 234 | }; 235 | const initialState = initialResourceState 236 | .setIn(['error', idHash], error) 237 | .setIn(['loading', idHash], promise); 238 | const newState = resourceReducer(initialState, action); 239 | expect(newState.getIn(['loading', idHash])).toBeUndefined(); 240 | expect(newState.getIn(['error', idHash])).toBeUndefined(); 241 | }); 242 | 243 | it('should handle LOAD_ERROR action', () => { 244 | const promise = Promise.resolve('completed'); 245 | const error = new Error('load error'); 246 | const idHash = getResourceIdHash(id); 247 | const action = { 248 | type: LOAD_ERROR, 249 | id, 250 | data: error, 251 | }; 252 | const initialState = initialResourceState.setIn(['loading', idHash], promise); 253 | const newState = resourceReducer(initialState, action); 254 | expect(newState.getIn(['loading', idHash])).toBeUndefined(); 255 | expect(newState.getIn(['error', idHash])).toEqual(error); 256 | }); 257 | 258 | it('handles CLEAR_COLLECTION action when collection exists', () => { 259 | const promise = Promise.resolve(); 260 | const otherId = { id: 456 }; 261 | const collectionIdHash = getCollectionIdHash({}); 262 | const resourceIdHash = getResourceIdHash(id); 263 | const otherResourceIdHash = getResourceIdHash(otherId); 264 | const action = { 265 | type: CLEAR_COLLECTION, 266 | id: 'someId', 267 | resource: 'users', 268 | opts: { query: 'value' }, 269 | }; 270 | const opts = { query: 'value' }; 271 | const otherOpts = { query1: 'value1' }; 272 | const queryHash = getQueryHash(opts); 273 | const otherQueryHash = getQueryHash(otherOpts); 274 | 275 | const initialState = initialResourceState 276 | .setIn( 277 | ['loading', collectionIdHash], 278 | iMap({ [queryHash]: promise }) 279 | ) 280 | .setIn( 281 | ['error', collectionIdHash], 282 | iMap({ [queryHash]: 'some error' }) 283 | ) 284 | .setIn( 285 | ['items', resourceIdHash], 286 | iMap({ prop: 'some value' }) 287 | ) 288 | .setIn( 289 | ['items', otherResourceIdHash], 290 | iMap({ prop: 'some other value' }) 291 | ) 292 | .setIn( 293 | ['collections', collectionIdHash, queryHash], 294 | iMap({ associatedIds: iList([resourceIdHash, otherResourceIdHash]) }) 295 | ) 296 | .setIn( 297 | ['collections', collectionIdHash, otherQueryHash], 298 | iMap({ associatedIds: iList([otherResourceIdHash]) }) 299 | ); 300 | 301 | const newState = resourceReducer(initialState, action); 302 | expect(newState.getIn(['loading', collectionIdHash, queryHash])).toBeUndefined(); 303 | expect(newState.getIn(['error', collectionIdHash, queryHash])).toBeUndefined(); 304 | expect(newState.getIn(['items']).size).toEqual(1); 305 | expect(newState.getIn(['items', otherResourceIdHash]).toJS()).toEqual({ prop: 'some other value' }); 306 | expect(newState.getIn(['collections', collectionIdHash, queryHash])).toBeUndefined(); 307 | expect(newState.getIn(['collections', collectionIdHash, otherQueryHash])).toBeDefined(); 308 | expect(newState.getIn(['collections', collectionIdHash, otherQueryHash, 'associatedIds']).toJS()) 309 | .toEqual([otherResourceIdHash]); 310 | }); 311 | 312 | it('CLEAR_COLLECTION does not crash if collection does not exist', () => { 313 | const collectionIdHash = getCollectionIdHash({}); 314 | const resourceIdHash = getResourceIdHash(id); 315 | const action = { 316 | type: CLEAR_COLLECTION, 317 | resource: 'users', 318 | opts: { query: 'value' }, 319 | }; 320 | const opts = { query: 'value' }; 321 | const queryHash = getQueryHash(opts); 322 | 323 | const newState = resourceReducer(initialResourceState, action); 324 | expect(newState.getIn(['loading', collectionIdHash, queryHash])).toBeUndefined(); 325 | expect(newState.getIn(['error', collectionIdHash, queryHash])).toBeUndefined(); 326 | expect(newState.getIn(['items', resourceIdHash])).toBeUndefined(); 327 | expect(newState.getIn(['collections', collectionIdHash, queryHash])).toBeUndefined(); 328 | }); 329 | 330 | it('should handle LOAD_COLLECTION_FINISHED action with a successful response', () => { 331 | const promise = Promise.resolve(); 332 | const collectionIdHash = getCollectionIdHash({}); 333 | const queryHash = getQueryHash(); 334 | const resourceIdHash = getResourceIdHash(id); 335 | const action = { 336 | type: LOAD_COLLECTION_FINISHED, 337 | resource: 'users', 338 | idHash: collectionIdHash, 339 | data: [{ id: '123' }], 340 | }; 341 | const opts = { query: 'value' }; 342 | const differentQueryHash = getQueryHash(opts); 343 | const initialState = initialResourceState.setIn( 344 | ['loading', collectionIdHash], 345 | iMap({ [queryHash]: promise, [differentQueryHash]: promise }) 346 | ); 347 | const newState = resourceReducer(initialState, action); 348 | expect(newState.getIn(['loading', collectionIdHash, queryHash])).toBeUndefined(); 349 | expect(newState.getIn(['loading', collectionIdHash, differentQueryHash])).toBeDefined(); 350 | expect(newState.getIn(['items', resourceIdHash]).toJS()).toEqual({ id: '123' }); 351 | expect(newState.getIn(['collections', collectionIdHash, queryHash]).toJS()) 352 | .toEqual({ associatedIds: [resourceIdHash] }); 353 | 354 | const updatedState = resourceReducer(newState, { 355 | type: LOAD_COLLECTION_FINISHED, 356 | resource: 'users', 357 | idHash: collectionIdHash, 358 | opts, 359 | data: '', 360 | }); 361 | expect(updatedState.getIn(['loading', collectionIdHash, differentQueryHash])).toBeUndefined(); 362 | }); 363 | 364 | it('should reset error on subsequent LOAD_COLLECTION_FINISHED success', () => { 365 | const promise = Promise.resolve(); 366 | const error = new Error('load error'); 367 | const collectionIdHash = getCollectionIdHash({}); 368 | const queryHash = getQueryHash(); 369 | const action = { 370 | type: LOAD_COLLECTION_FINISHED, 371 | resource: 'users', 372 | idHash: collectionIdHash, 373 | data: [{ id: '123' }], 374 | }; 375 | const initialState = initialResourceState 376 | .setIn(['collections', collectionIdHash, queryHash, 'error'], error) 377 | .setIn(['loading', collectionIdHash], iMap({ [queryHash]: promise })); 378 | 379 | const newState = resourceReducer(initialState, action); 380 | expect(newState.getIn(['loading', collectionIdHash, queryHash])).toBeUndefined(); 381 | expect(newState.getIn(['collections', collectionIdHash, queryHash, 'error'])).toBeUndefined(); 382 | }); 383 | 384 | it('should handle LOAD_COLLECTION_ERROR action', () => { 385 | const promise = Promise.resolve(); 386 | const error = new Error('load error'); 387 | const collectionIdHash = getCollectionIdHash({}); 388 | const queryHash = getQueryHash(); 389 | const action = { 390 | type: LOAD_COLLECTION_ERROR, 391 | resource: 'users', 392 | idHash: collectionIdHash, 393 | data: error, 394 | }; 395 | const opts = { query: 'value' }; 396 | const differentQueryHash = getQueryHash(opts); 397 | const initialState = initialResourceState.setIn( 398 | ['loading', collectionIdHash], 399 | iMap({ [queryHash]: promise, [differentQueryHash]: promise }) 400 | ); 401 | const newState = resourceReducer(initialState, action); 402 | expect(newState.getIn(['loading', collectionIdHash, queryHash])).toBeUndefined(); 403 | expect(newState.getIn(['loading', collectionIdHash, differentQueryHash])).toBeDefined(); 404 | expect(newState.getIn(['collections', collectionIdHash, queryHash, 'error'])).toEqual(error); 405 | 406 | const updatedState = resourceReducer(newState, { 407 | type: LOAD_COLLECTION_ERROR, 408 | resource: 'users', 409 | idHash: collectionIdHash, 410 | opts, 411 | data: error, 412 | }); 413 | expect(updatedState.getIn(['loading', collectionIdHash, differentQueryHash])).toBeUndefined(); 414 | expect(updatedState.getIn(['collections', collectionIdHash, differentQueryHash, 'error'])) 415 | .toEqual(error); 416 | }); 417 | 418 | it('should handle CREATE_FINISHED action', () => { 419 | const action = { 420 | type: CREATE_FINISHED, 421 | resource: 'users', 422 | data: { id: '123' }, 423 | }; 424 | const initialState = initialResourceState 425 | .set('isCreating', true) 426 | .set('collections', iMap({ idHash: { queryHash: { associatedIds: ['a', 'b'] } } })); 427 | const newState = resourceReducer(initialState, action); 428 | expect(newState.get('isCreating')).toBe(false); 429 | expect(newState.getIn(['items', getResourceIdHash(id)]).toJS()).toEqual({ id: '123' }); 430 | expect(newState.get('collections')).toEqual(iMap()); 431 | }); 432 | 433 | it('should handle CREATE_ERROR action', () => { 434 | const error = new Error('load error'); 435 | const action = { 436 | type: CREATE_ERROR, 437 | resource: 'users', 438 | data: error, 439 | }; 440 | const initialCollection = iMap({ idHash: { queryHash: { associatedIds: ['a', 'b'] } } }); 441 | const initialState = initialResourceState 442 | .set('isCreating', true) 443 | .set('collections', initialCollection); 444 | const newState = resourceReducer(initialState, action); 445 | expect(newState.get('isCreating')).toBe(false); 446 | expect(newState.getIn(['items', getResourceIdHash(id)])).toBeUndefined(); 447 | expect(newState.get('collections')).toEqual(initialCollection); 448 | }); 449 | 450 | it('should handle UPDATE_FINISHED action', () => { 451 | const promise = Promise.resolve(); 452 | const idHash = getResourceIdHash(id); 453 | const action = { 454 | type: UPDATE_FINISHED, 455 | id, 456 | data: { id: '123' }, 457 | }; 458 | const initialState = initialResourceState.setIn(['updating', idHash], promise); 459 | const newState = resourceReducer(initialState, action); 460 | expect(newState.getIn(['updating', idHash])).toBeUndefined(); 461 | expect(newState.getIn(['items', idHash]).toJS()).toEqual({ id: '123' }); 462 | }); 463 | 464 | it('should handle UPDATE_ERROR action', () => { 465 | const promise = Promise.resolve(); 466 | const error = new Error('load error'); 467 | const idHash = getResourceIdHash(id); 468 | const action = { 469 | type: UPDATE_ERROR, 470 | id, 471 | data: error, 472 | }; 473 | const initialState = initialResourceState.setIn(['updating', idHash], promise); 474 | const newState = resourceReducer(initialState, action); 475 | expect(newState.getIn(['updating', idHash])).toBeUndefined(); 476 | expect(newState.getIn(['items', idHash])).toBeUndefined(); 477 | }); 478 | 479 | it('should handle UPDATE_COLLECTION_FINISHED action with a successful response', () => { 480 | const promise = Promise.resolve(); 481 | const collectionIdHash = getCollectionIdHash({}); 482 | const queryHash = getQueryHash(); 483 | const resourceIdHash = getResourceIdHash(id); 484 | const action = { 485 | type: UPDATE_COLLECTION_FINISHED, 486 | resource: 'users', 487 | idHash: collectionIdHash, 488 | data: [{ id: '123' }], 489 | }; 490 | const opts = { query: 'value' }; 491 | const differentQueryHash = getQueryHash(opts); 492 | const initialState = initialResourceState.setIn( 493 | ['updating', collectionIdHash], 494 | iMap({ [queryHash]: promise, [differentQueryHash]: promise }) 495 | ); 496 | const newState = resourceReducer(initialState, action); 497 | expect(newState.getIn(['updating', collectionIdHash, queryHash])).toBeUndefined(); 498 | expect(newState.getIn(['updating', collectionIdHash, differentQueryHash])).toBeDefined(); 499 | expect(newState.getIn(['items', resourceIdHash]).toJS()).toEqual({ id: '123' }); 500 | 501 | const updatedState = resourceReducer(newState, { 502 | type: UPDATE_COLLECTION_FINISHED, 503 | resource: 'users', 504 | idHash: collectionIdHash, 505 | opts, 506 | data: '', 507 | }); 508 | expect(updatedState.getIn(['updating', collectionIdHash, differentQueryHash])).toBeUndefined(); 509 | }); 510 | 511 | it('should reset error on subsequent UPDATE_COLLECTION_FINISHED success', () => { 512 | const promise = Promise.resolve(); 513 | const error = new Error('load error'); 514 | const collectionIdHash = getCollectionIdHash({}); 515 | const queryHash = getQueryHash(); 516 | const action = { 517 | type: UPDATE_COLLECTION_FINISHED, 518 | resource: 'users', 519 | idHash: collectionIdHash, 520 | data: [{ id: '123' }], 521 | }; 522 | const initialState = initialResourceState 523 | .setIn(['collections', collectionIdHash, queryHash, 'error'], error) 524 | .setIn(['updating', collectionIdHash], iMap({ [queryHash]: promise })); 525 | 526 | const newState = resourceReducer(initialState, action); 527 | expect(newState.getIn(['updating', collectionIdHash, queryHash])).toBeUndefined(); 528 | }); 529 | 530 | it('should handle UPDATE_COLLECTION_ERROR action', () => { 531 | const promise = Promise.resolve(); 532 | const error = new Error('update error'); 533 | const collectionIdHash = getCollectionIdHash({}); 534 | const queryHash = getQueryHash(); 535 | const action = { 536 | type: UPDATE_COLLECTION_ERROR, 537 | resource: 'users', 538 | idHash: collectionIdHash, 539 | data: error, 540 | }; 541 | const opts = { query: 'value' }; 542 | const differentQueryHash = getQueryHash(opts); 543 | const initialState = initialResourceState.setIn( 544 | ['updating', collectionIdHash], 545 | iMap({ [queryHash]: promise, [differentQueryHash]: promise }) 546 | ); 547 | const newState = resourceReducer(initialState, action); 548 | expect(newState.getIn(['updating', collectionIdHash, queryHash])).toBeUndefined(); 549 | expect(newState.getIn(['updating', collectionIdHash, differentQueryHash])).toBeDefined(); 550 | 551 | const updatedState = resourceReducer(newState, { 552 | type: UPDATE_COLLECTION_ERROR, 553 | resource: 'users', 554 | idHash: collectionIdHash, 555 | opts, 556 | data: error, 557 | }); 558 | expect(updatedState.getIn(['updating', collectionIdHash, differentQueryHash])).toBeUndefined(); 559 | }); 560 | 561 | it('should handle DESTROY_FINISHED action', () => { 562 | const promise = Promise.resolve(); 563 | const idHash = getResourceIdHash(id); 564 | const action = { 565 | type: DESTROY_FINISHED, 566 | id, 567 | }; 568 | const initialState = initialResourceState 569 | .setIn(['destroying', idHash], promise) 570 | .set('collections', fromJS({ idHash: { queryHash: { associatedIds: [idHash] } } })); 571 | const newState = resourceReducer(initialState, action); 572 | expect(newState.getIn(['destroying', idHash])).toBeUndefined(); 573 | expect(newState.getIn(['items', idHash])).toBeUndefined(); 574 | expect(newState.getIn(['collections', 'idHash', 'queryHash', 'associatedIds']).includes(idHash)).toBe(false); 575 | }); 576 | 577 | it('shouldnt destroy unrelated resources', () => { 578 | const promise = Promise.resolve(); 579 | const deleteId = { id: '123' }; 580 | const idHash = getResourceIdHash(deleteId); 581 | 582 | const associatedId = { id: '456' }; 583 | const associatedIdHash = getResourceIdHash(associatedId); 584 | 585 | const action = { 586 | type: DESTROY_FINISHED, 587 | id: deleteId, 588 | }; 589 | const initialState = initialResourceState 590 | .setIn(['destroying', idHash], promise) 591 | .set('collections', fromJS({ 592 | idHash: { 593 | queryHash: { associatedIds: [idHash] }, 594 | relatedQueryHash: { associatedIds: [associatedIdHash] }, 595 | }, 596 | })); 597 | const newState = resourceReducer(initialState, action); 598 | expect(newState.getIn(['destroying', idHash])).toBeUndefined(); 599 | expect(newState.getIn(['items', idHash])).toBeUndefined(); 600 | expect(newState.getIn(['collections', 'idHash', 'queryHash', 'associatedIds']).includes(idHash)).toBe(false); 601 | expect(newState.getIn(['collections', 'idHash', 'relatedQueryHash', 'associatedIds']).includes(associatedIdHash)).toBe(true); 602 | }); 603 | 604 | it('should handle DESTROY_ERROR action', () => { 605 | const promise = Promise.resolve(); 606 | const error = new Error('load error'); 607 | const idHash = getResourceIdHash(id); 608 | const action = { 609 | type: DESTROY_ERROR, 610 | id, 611 | data: error, 612 | }; 613 | const initialItems = { [idHash]: id }; 614 | const initialCollection = fromJS({ idHash: { queryHash: { associatedIds: [idHash] } } }); 615 | const initialState = initialResourceState 616 | .setIn(['destroying', idHash], promise) 617 | .set('items', initialItems) 618 | .set('collections', initialCollection); 619 | const newState = resourceReducer(initialState, action); 620 | expect(newState.getIn(['destroying', idHash])).toBeUndefined(); 621 | expect(newState.get('items')).toEqual(initialItems); 622 | expect(newState.get('collections')).toEqual(initialCollection); 623 | }); 624 | 625 | it('should return previous state for irrelevant actions', () => { 626 | const state = 'state'; 627 | const action = { type: 'IRRELEVANT_ACTION' }; 628 | expect(resourceReducer(state, action)).toEqual(state); 629 | }); 630 | 631 | it('should handle PATCH_FINISHED action', () => { 632 | const promise = Promise.resolve(); 633 | const idHash = getResourceIdHash(id); 634 | const action = { 635 | type: PATCH_FINISHED, 636 | id, 637 | data: { id: '123' }, 638 | }; 639 | const initialState = initialResourceState.setIn(['updating', idHash], promise); 640 | const newState = resourceReducer(initialState, action); 641 | expect(newState.getIn(['updating', idHash])).toBeUndefined(); 642 | expect(newState.getIn(['items', idHash]).toJS()).toEqual({ id: '123' }); 643 | }); 644 | 645 | it('should handle PATCH_ERROR action', () => { 646 | const promise = Promise.resolve(); 647 | const error = new Error('load error'); 648 | const idHash = getResourceIdHash(id); 649 | const action = { 650 | type: PATCH_ERROR, 651 | id, 652 | data: error, 653 | }; 654 | const initialState = initialResourceState.setIn(['updating', idHash], promise); 655 | const newState = resourceReducer(initialState, action); 656 | expect(newState.getIn(['updating', idHash])).toBeUndefined(); 657 | expect(newState.getIn(['items', idHash])).toBeUndefined(); 658 | }); 659 | }); 660 | 661 | describe('resourcesReducer', () => { 662 | it('should reset to initial state for RESET action', () => { 663 | const state = 'state'; 664 | const action = { type: RESET }; 665 | const reducer = resourcesReducer; 666 | expect(reducer(state, action)).toEqual(iMap()); 667 | }); 668 | 669 | it('should update a resources state on a resource action', () => { 670 | const state = iMap(); 671 | const action = { 672 | type: CREATE_STARTED, 673 | resource: 'users', 674 | }; 675 | const reducer = resourcesReducer; 676 | const newState = reducer(state, action); 677 | expect(newState.getIn(['users', 'isCreating'])).toBe(true); 678 | }); 679 | 680 | it('should return the previous state for irrelevant actions', () => { 681 | const state = 'state'; 682 | const action = { type: 'IRRELEVANT_ACTION' }; 683 | const reducer = resourcesReducer; 684 | expect(reducer(state, action)).toEqual(state); 685 | }); 686 | 687 | it('should set up the correct initial state', () => { 688 | const reducer = resourcesReducer; 689 | const action = { type: '@@redux/INIT' }; 690 | expect(reducer(undefined, action)).toEqual(iMap()); 691 | }); 692 | }); 693 | 694 | describe('flows', () => { 695 | it('clears the collection loading state after all queries are finished', () => { 696 | let state = resourcesReducer(undefined, { type: '@@init' }); 697 | const optsA = { query: { a: 1 } }; 698 | const optsB = { query: { b: 2 } }; 699 | const optsC = { query: { c: 3 } }; 700 | // start A, B, C 701 | state = resourcesReducer(state, { 702 | type: LOAD_COLLECTION_STARTED, resource: 'users', id, opts: optsA, promise: Promise.resolve(), 703 | }); 704 | state = resourcesReducer(state, { 705 | type: LOAD_COLLECTION_STARTED, resource: 'users', id, opts: optsB, promise: Promise.resolve(), 706 | }); 707 | state = resourcesReducer(state, { 708 | type: LOAD_COLLECTION_STARTED, resource: 'users', id, opts: optsC, promise: Promise.resolve(), 709 | }); 710 | // finish A, C, B to ensure order doesn't matter 711 | state = resourcesReducer(state, { 712 | type: LOAD_COLLECTION_FINISHED, resource: 'users', id, data: [], opts: optsA, 713 | }); 714 | state = resourcesReducer(state, { 715 | type: LOAD_COLLECTION_FINISHED, resource: 'users', id, data: [], opts: optsC, 716 | }); 717 | state = resourcesReducer(state, { 718 | type: LOAD_COLLECTION_FINISHED, resource: 'users', id, data: [], opts: optsB, 719 | }); 720 | expect(state.getIn(['users', 'loading'])).toEqual(iMap()); 721 | }); 722 | 723 | it('does not die on race conditions of successful loads', () => { 724 | let state = resourcesReducer(undefined, { type: '@@init' }); 725 | const optsA = { query: { a: 1 } }; 726 | const optsB = { query: { b: 2 } }; 727 | // start A, B, A, B 728 | state = resourcesReducer(state, { 729 | type: LOAD_COLLECTION_STARTED, resource: 'users', id, opts: optsA, promise: Promise.resolve(), 730 | }); 731 | state = resourcesReducer(state, { 732 | type: LOAD_COLLECTION_STARTED, resource: 'users', id, opts: optsB, promise: Promise.resolve(), 733 | }); 734 | state = resourcesReducer(state, { 735 | type: LOAD_COLLECTION_STARTED, resource: 'users', id, opts: optsA, promise: Promise.resolve(), 736 | }); 737 | state = resourcesReducer(state, { 738 | type: LOAD_COLLECTION_STARTED, resource: 'users', id, opts: optsB, promise: Promise.resolve(), 739 | }); 740 | // finish B, B, A, A to ensure order doesn't matter 741 | state = resourcesReducer(state, { 742 | type: LOAD_COLLECTION_FINISHED, resource: 'users', id, data: [], opts: optsB, 743 | }); 744 | state = resourcesReducer(state, { 745 | type: LOAD_COLLECTION_FINISHED, resource: 'users', id, data: [], opts: optsB, 746 | }); 747 | state = resourcesReducer(state, { 748 | type: LOAD_COLLECTION_FINISHED, resource: 'users', id, data: [], opts: optsA, 749 | }); 750 | state = resourcesReducer(state, { 751 | type: LOAD_COLLECTION_FINISHED, resource: 'users', id, data: [], opts: optsA, 752 | }); 753 | expect(state.getIn(['users', 'loading'])).toEqual(iMap()); 754 | }); 755 | 756 | it('does not die on race conditions of unsuccessful loads', () => { 757 | let state = resourcesReducer(undefined, { type: '@@init' }); 758 | const optsA = { query: { a: 1 } }; 759 | const optsB = { query: { b: 2 } }; 760 | // start A, B, A, B 761 | state = resourcesReducer(state, { 762 | type: LOAD_COLLECTION_STARTED, resource: 'users', id, opts: optsA, promise: Promise.resolve(), 763 | }); 764 | state = resourcesReducer(state, { 765 | type: LOAD_COLLECTION_STARTED, resource: 'users', id, opts: optsB, promise: Promise.resolve(), 766 | }); 767 | state = resourcesReducer(state, { 768 | type: LOAD_COLLECTION_STARTED, resource: 'users', id, opts: optsA, promise: Promise.resolve(), 769 | }); 770 | state = resourcesReducer(state, { 771 | type: LOAD_COLLECTION_STARTED, resource: 'users', id, opts: optsB, promise: Promise.resolve(), 772 | }); 773 | // finish B, B, A, A to ensure order doesn't matter 774 | state = resourcesReducer(state, { 775 | type: LOAD_COLLECTION_ERROR, resource: 'users', id, data: new Error('oh no'), opts: optsB, 776 | }); 777 | state = resourcesReducer(state, { 778 | type: LOAD_COLLECTION_ERROR, resource: 'users', id, data: new Error('oh no'), opts: optsB, 779 | }); 780 | state = resourcesReducer(state, { 781 | type: LOAD_COLLECTION_ERROR, resource: 'users', id, data: new Error('oh no'), opts: optsA, 782 | }); 783 | state = resourcesReducer(state, { 784 | type: LOAD_COLLECTION_ERROR, resource: 'users', id, data: new Error('oh no'), opts: optsA, 785 | }); 786 | expect(state.getIn(['users', 'loading'])).toEqual(iMap()); 787 | }); 788 | }); 789 | }); 790 | --------------------------------------------------------------------------------