├── .travis.yml ├── index.js ├── .github ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── CONTRIBUTING.md ├── src ├── constants.js └── base.js ├── package.json ├── .gitignore ├── .eslintrc.js ├── CODE_OF_CONDUCT.md ├── README.md ├── LICENSE └── test └── base.test.js /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | sudo: false 3 | git: 4 | depth: 10 5 | 6 | os: 7 | - windows 8 | - linux 9 | 10 | node_js: 11 | - '8' 12 | - '10' 13 | - '12' 14 | 15 | install: 16 | - npm version 17 | - npm install -g codecov 18 | - npm install 19 | 20 | script: 21 | - npm test 22 | 23 | after_success: 24 | - codecov 25 | 26 | # safelist (prevent double builds in PRs) 27 | branches: 28 | only: 29 | - master 30 | - /^greenkeeper.*$/ 31 | 32 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | module.exports = { 14 | BaseClient: require('./src/base') 15 | }; 16 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ### Expected Behaviour 5 | 6 | ### Actual Behaviour 7 | 8 | ### Reproduce Scenario (including but not limited to) 9 | 10 | #### Steps to Reproduce 11 | 12 | #### Platform and Version 13 | 14 | #### Sample Code that illustrates the problem 15 | 16 | #### Logs taken while reproducing problem -------------------------------------------------------------------------------- /src/constants.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | module.exports = { 14 | DEFAULT_GATEWAY: 'https://platform.adobe.io' 15 | }; 16 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@adobe/api-client-base", 3 | "version": "0.3.2", 4 | "description": "Adobe API Base Client for NodeJS", 5 | "main": "index.js", 6 | "scripts": { 7 | "lint": "eslint src test index.js", 8 | "test": "jest" 9 | }, 10 | "repository": { 11 | "type": "git", 12 | "url": "https://github.com/adobe/adobe-api-client-base.git" 13 | }, 14 | "bugs": { 15 | "url": "https://github.com/adobe/adobe-api-client-base/issues" 16 | }, 17 | "engines": { 18 | "node": ">=6.0.0" 19 | }, 20 | "keywords": [ 21 | "AEP", 22 | "API", 23 | "adobe.io" 24 | ], 25 | "author": "Ittai Baratz", 26 | "license": "Apache-2.0", 27 | "publishConfig": { 28 | "registry": "https://registry.npmjs.org" 29 | }, 30 | "dependencies": { 31 | "@adobe/api-fetch": "^0.3.1", 32 | "debug": "^4.1.1" 33 | }, 34 | "devDependencies": { 35 | "eslint": "^6.6.0", 36 | "eslint-config-prettier": "^6.7.0", 37 | "eslint-plugin-prettier": "^3.1.0", 38 | "jest": "^24.9.0", 39 | "node-fetch": "^2.6.0", 40 | "prettier": "^1.19.1" 41 | }, 42 | "jest": { 43 | "coverageDirectory": "./coverage/", 44 | "collectCoverage": true 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | .node-persist 63 | .DS_Store 64 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | module.exports = { 14 | extends: ['eslint:recommended', 'prettier'], // extending recommended config and config derived from eslint-config-prettier 15 | plugins: ['prettier'], // activating esling-plugin-prettier (--fix stuff) 16 | parserOptions: { 17 | ecmaVersion: 2017 18 | }, 19 | 20 | env: { 21 | es6: true, 22 | jest: true, 23 | node: true 24 | }, 25 | rules: { 26 | 'prettier/prettier': [ 27 | // customizing prettier rules (unfortunately not many of them are customizable) 28 | 'error', 29 | { 30 | singleQuote: true, 31 | trailingComma: 'none' 32 | } 33 | ], 34 | eqeqeq: ['error', 'always'] // adding some custom ESLint rules 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Description 4 | 5 | 6 | 7 | ## Related Issue 8 | 9 | 10 | 11 | 12 | 13 | 14 | ## Motivation and Context 15 | 16 | 17 | 18 | ## How Has This Been Tested? 19 | 20 | 21 | 22 | 23 | 24 | ## Screenshots (if appropriate): 25 | 26 | ## Types of changes 27 | 28 | 29 | 30 | - [ ] Bug fix (non-breaking change which fixes an issue) 31 | - [ ] New feature (non-breaking change which adds functionality) 32 | - [ ] Breaking change (fix or feature that would cause existing functionality to change) 33 | 34 | ## Checklist: 35 | 36 | 37 | 38 | 39 | - [ ] I have signed the [Adobe Open Source CLA](http://opensource.adobe.com/cla.html). 40 | - [ ] My code follows the code style of this project. 41 | - [ ] My change requires a change to the documentation. 42 | - [ ] I have updated the documentation accordingly. 43 | - [ ] I have read the **CONTRIBUTING** document. 44 | - [ ] I have added tests to cover my changes. 45 | - [ ] All new and existing tests passed. -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Thanks for choosing to contribute! 4 | 5 | The following are a set of guidelines to follow when contributing to this project. 6 | 7 | ## Code Of Conduct 8 | 9 | This project adheres to the Adobe [code of conduct](../CODE_OF_CONDUCT.md). By participating, 10 | you are expected to uphold this code. Please report unacceptable behavior to 11 | [Grp-opensourceoffice@adobe.com](mailto:Grp-opensourceoffice@adobe.com). 12 | 13 | ## Have A Question? 14 | 15 | Start by filing an issue. The existing committers on this project work to reach 16 | consensus around project direction and issue solutions within issue threads 17 | (when appropriate). 18 | 19 | ## Contributor License Agreement 20 | 21 | All third-party contributions to this project must be accompanied by a signed contributor 22 | license agreement. This gives Adobe permission to redistribute your contributions 23 | as part of the project. [Sign our CLA](http://opensource.adobe.com/cla.html). You 24 | only need to submit an Adobe CLA one time, so if you have submitted one previously, 25 | you are good to go! 26 | 27 | ## Code Reviews 28 | 29 | All submissions should come in the form of pull requests and need to be reviewed 30 | by project committers. Read [GitHub's pull request documentation](https://help.github.com/articles/about-pull-requests/) 31 | for more information on sending pull requests. 32 | 33 | Lastly, please follow the [pull request template](PULL_REQUEST_TEMPLATE.md) when 34 | submitting a pull request! 35 | 36 | ## From Contributor To Committer 37 | 38 | We love contributions from our community! If you'd like to go a step beyond contributor 39 | and become a committer with full write access and a say in the project, you must 40 | be invited to the project. The existing committers employ an internal nomination 41 | process that must reach lazy consensus (silence is approval) before invitations 42 | are issued. If you feel you are qualified and want to get more deeply involved, 43 | feel free to reach out to existing committers to have a conversation about that. 44 | 45 | ## Security Issues 46 | 47 | Security issues shouldn't be reported on this issue tracker. Instead, [file an issue to our security experts](https://helpx.adobe.com/security/alertus.html) -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Adobe Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | - Using welcoming and inclusive language 18 | - Being respectful of differing viewpoints and experiences 19 | - Gracefully accepting constructive criticism 20 | - Focusing on what is best for the community 21 | - Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | - The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | - Trolling, insulting/derogatory comments, and personal or political attacks 28 | - Public or private harassment 29 | - Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | - Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at Grp-opensourceoffice@adobe.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [https://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: https://contributor-covenant.org 74 | [version]: https://contributor-covenant.org/version/1/4/ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 2 | [![Version](https://img.shields.io/npm/v/@adobe/api-client-base.svg)](https://npmjs.org/package/@adobe/api-client-base) 3 | [![Downloads/week](https://img.shields.io/npm/dw/@adobe/api-client-base.svg)](https://npmjs.org/package/@adobe/api-client-base) 4 | [![Build Status](https://travis-ci.org/adobe/adobe-api-client-base.svg?branch=master)](https://travis-ci.com/adobe/adobe-api-client-base) 5 | [![codecov](https://codecov.io/gh/adobe/adobe-api-client-base/branch/master/graph/badge.svg)](https://codecov.io/gh/adobe/adobe-api-client-base) 6 | [![Greenkeeper badge](https://badges.greenkeeper.io/adobe/adobe-api-client-base.svg)](https://greenkeeper.io/) 7 | [![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/adobe/adobe-api-client-base.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/adobe/adobe-api-client-base/context:javascript) 8 | 9 | # adobe-api-client-base 10 | 11 | Base class for building Adobe API clients 12 | 13 | ## Goals 14 | 15 | A base class for building API clients for Adobe solutions running on the Adobe.IO API gateway. 16 | 17 | This package is build upon [adobe-fetch](https://github.com/adobe/adobe-fetch) which handles the low level API call, JWT authentication, token caching and storage. 18 | 19 | ### Installation 20 | 21 | ``` 22 | npm install --save @adobe/api-client-base 23 | ``` 24 | 25 | ### Common Usage 26 | 27 | * Option A - Provide an adobefetch instance: 28 | 29 | ```javascript 30 | 31 | const { BaseClient } = require('@adobe/api-client-base'); 32 | 33 | const config = { 34 | auth: { ... See adobe/fetch documentation for details ... } 35 | }; 36 | 37 | const adobefetch = require('@adobe/fetch').config(config); 38 | const client = new BaseClient(adobefetch, { rootPath: '/path/to/api' }); 39 | 40 | ``` 41 | 42 | * Option B - Provide the auth configuration, adobefetch will be instantiated automatically: 43 | 44 | ```javascript 45 | 46 | const { BaseClient } = require('@adobe/api-client-base'); 47 | 48 | const client = new BaseClient(adobefetch, { 49 | auth: { ... See adobe/fetch documentation for details ... }, 50 | rootPath: '/path/to/api' 51 | }); 52 | 53 | ``` 54 | 55 | #### Creating your own API client class 56 | 57 | To create your own API client class, extend BaseClient and override the default options function. 58 | Then you can create helper methods for calling specific APIs. 59 | 60 | For example: 61 | 62 | ```javascript 63 | 64 | const { BaseClient } = require('@adobe/api-client-base'); 65 | 66 | class MyApiClient extends BaseClient { 67 | constructor(fetch, opts) { 68 | super(fetch, opts); 69 | this.someParameter = opts.someParameter; 70 | } 71 | 72 | _default() { 73 | return { 74 | name: 'myapi', 75 | gateway: 'https://myapi.adobe.io', 76 | rootPath: '/path/to/api', 77 | headers: { 78 | 'x-some-header': 'some-value' 79 | } 80 | }; 81 | } 82 | 83 | // Call https://myapi.adobe.io/path/to/api/foo/bar 84 | getFooBar(parameters = {}) { 85 | const path = this.addParamsToPath('/foo/bar', parameters); 86 | return this.get(path); 87 | } 88 | ``` 89 | 90 | ### Contributing 91 | 92 | Contributions are welcomed! Read the [Contributing Guide](.github/CONTRIBUTING.md) for more information. 93 | 94 | ### Licensing 95 | 96 | This project is licensed under the Apache V2 License. See [LICENSE](LICENSE) for more information. 97 | -------------------------------------------------------------------------------- /src/base.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | const adobefetch = require('@adobe/fetch'); 13 | const Constants = require('./constants'); 14 | const querystring = require('querystring'); 15 | const Debug = require('debug'); 16 | 17 | module.exports = class baseAPIClient { 18 | constructor(fetch = {}, opts) { 19 | if (typeof fetch === 'object') { 20 | opts = fetch; 21 | if (!opts.auth) { 22 | throw 'No configuration provided.'; 23 | } 24 | fetch = adobefetch.config({ auth: opts.auth }); 25 | } 26 | 27 | if (!opts) { 28 | opts = this._default(); 29 | } 30 | 31 | this.name = opts.name ? opts.name : this._default().name; 32 | this.rootPath = opts.rootPath ? opts.rootPath : this._default().rootPath; 33 | 34 | this.debug = Debug(`aep-api-client:${this.name}`); 35 | this.fetch = fetch; 36 | this.opts = opts; 37 | const gateway = 38 | opts.gateway || this._default().gateway || Constants.DEFAULT_GATEWAY; 39 | this.gateway = gateway.replace(/\/$/, ''); 40 | this.endpoint = `${this.gateway}${this.rootPath}`; 41 | this.headers = adobefetch.normalizeHeaders(this._default().headers); 42 | 43 | if (opts.headers) { 44 | this.headers = Object.assign( 45 | this.headers, 46 | adobefetch.normalizeHeaders(opts.headers) 47 | ); 48 | } 49 | } 50 | 51 | _default() { 52 | return { 53 | name: 'base', 54 | rootPath: '', 55 | headers: { 56 | 'cache-control': 'no-cache' 57 | } 58 | }; 59 | } 60 | 61 | ensurePrefix(path) { 62 | return path.substr(0, 1) !== '/' ? `/${path}` : path; 63 | } 64 | 65 | addParamsToPath(path, params) { 66 | if (params) { 67 | const [basePath, query] = path.split('?'); 68 | if (query) { 69 | const existingParams = querystring.parse(query); 70 | params = Object.assign(existingParams, params); 71 | } 72 | return `${basePath}?${querystring.stringify(params)}`; 73 | } else { 74 | return path; 75 | } 76 | } 77 | 78 | async api(path, method = 'GET', returnsJson = true, options = {}, payload) { 79 | let url = path.startsWith(this.endpoint) 80 | ? path 81 | : `${this.endpoint}${this.ensurePrefix(path)}`; 82 | let response; 83 | 84 | try { 85 | this.debug(`Fetch ${url}`); 86 | if (!options.headers) { 87 | options.headers = this.headers; 88 | } else { 89 | let headers = Object.assign({}, this.headers); 90 | headers = Object.assign( 91 | headers, 92 | adobefetch.normalizeHeaders(options.headers) 93 | ); 94 | options.headers = headers; 95 | } 96 | options.method = method; 97 | 98 | if (payload) { 99 | options.body = JSON.stringify(payload); 100 | if (!options.headers['content-type']) { 101 | options.headers['content-type'] = 'application/json'; 102 | } 103 | } 104 | 105 | response = await this.fetch(url, options); 106 | } catch (err) { 107 | this.debug(`Fetch ${url} failed: ${err}`); 108 | throw { 109 | error: err.toString(), 110 | status: 0 111 | }; 112 | } 113 | 114 | if (response) { 115 | if (response.ok) { 116 | if (returnsJson) { 117 | return await response.json(); 118 | } else { 119 | return response; 120 | } 121 | } else { 122 | throw { 123 | error: response.statusText || 'Unknown error', 124 | status: response.status || 0 125 | }; 126 | } 127 | } else { 128 | this.debug(`Fetch ${path} failed: Empty response.`); 129 | throw { 130 | error: 'Empty response', 131 | status: 0 132 | }; 133 | } 134 | } 135 | 136 | async get(path, returnJson = true, options = {}) { 137 | return this.api(path, 'GET', returnJson, options); 138 | } 139 | 140 | async post(path, payload, returnJson = true, options = {}) { 141 | return this.api(path, 'POST', returnJson, options, payload); 142 | } 143 | 144 | async patch(path, payload, returnJson = true, options = {}) { 145 | return this.api(path, 'PATCH', returnJson, options, payload); 146 | } 147 | 148 | async put(path, payload, returnJson = true, options = {}) { 149 | return this.api(path, 'PUT', returnJson, options, payload); 150 | } 151 | 152 | async delete(path, payload, returnJson = true, options = {}) { 153 | return this.api(path, 'DELETE', returnJson, options, payload); 154 | } 155 | }; 156 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 2019 Adobe 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /test/base.test.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | const adobefetch = require('@adobe/fetch'); 14 | const { Headers } = require.requireActual('node-fetch'); 15 | const { BaseClient } = require('../index'); 16 | 17 | const AUTH_ONLY_OPTS = { auth: { test: 'this' } }; 18 | const DEFAULT_OPTS = { 19 | rootPath: '/my/api', 20 | auth: { this: 'this' } 21 | }; 22 | 23 | const OPTS_WITH_HEADER = { 24 | auth: { test: 'this' }, 25 | rootPath: '/my/api', 26 | headers: { 27 | 'Some-Header': 'Some Value' 28 | } 29 | }; 30 | 31 | adobefetch.normalizeHeaders = require.requireActual( 32 | '@adobe/fetch' 33 | ).normalizeHeaders; 34 | 35 | jest.mock('@adobe/fetch'); 36 | 37 | function mockFetch(validationFn, returnValue, configValidationFn) { 38 | adobefetch.config.mockImplementation(fetchOpts => { 39 | if (typeof configValidationFn === 'function') { 40 | configValidationFn(fetchOpts); 41 | } 42 | return async (url, options) => { 43 | if (typeof validationFn === 'function') { 44 | validationFn(url, options); 45 | } 46 | if (returnValue) { 47 | if (typeof returnValue === 'function') { 48 | return returnValue(url, options); 49 | } else { 50 | return returnValue; 51 | } 52 | } else { 53 | return { 54 | ok: true, 55 | json: async () => { 56 | return { 57 | result: 'some result' 58 | }; 59 | } 60 | }; 61 | } 62 | }; 63 | }); 64 | } 65 | 66 | describe('Validate constructor', () => { 67 | test('Creates fetch from config', async () => { 68 | expect.assertions(1); 69 | mockFetch(undefined, undefined, fetchOpts => 70 | expect(fetchOpts.auth.test).toBe('this') 71 | ); 72 | const client = new BaseClient(AUTH_ONLY_OPTS); 73 | await client.get('/some/url'); 74 | }); 75 | 76 | test('Uses given fetch', async () => { 77 | expect.assertions(1); 78 | mockFetch(undefined, undefined, fetchOpts => 79 | expect(fetchOpts.auth.test).toBe('this') 80 | ); 81 | const fetch = adobefetch.config(AUTH_ONLY_OPTS); 82 | const client = new BaseClient(fetch, { rootPath: '/my/api' }); 83 | await client.get('/some/url'); 84 | }); 85 | 86 | test('Uses default configuration', async () => { 87 | expect.assertions(1); 88 | mockFetch(url => expect(url).toBe('https://platform.adobe.io/some/url')); 89 | const fetch = adobefetch.config(AUTH_ONLY_OPTS); 90 | const client = new BaseClient(fetch); 91 | await client.get('/some/url'); 92 | }); 93 | 94 | test('Override gateway', async () => { 95 | expect.assertions(1); 96 | mockFetch(url => expect(url).toBe('https://test.adobe.io/some/url')); 97 | const fetch = adobefetch.config(AUTH_ONLY_OPTS); 98 | const client = new BaseClient(fetch, { 99 | gateway: 'https://test.adobe.io' 100 | }); 101 | await client.get('/some/url'); 102 | }); 103 | 104 | test('Uses given configuration', async () => { 105 | expect.assertions(1); 106 | mockFetch(url => 107 | expect(url).toBe('https://platform.adobe.io/my/api/some/url') 108 | ); 109 | const fetch = adobefetch.config(AUTH_ONLY_OPTS); 110 | const client = new BaseClient(fetch, { rootPath: '/my/api' }); 111 | await client.get('/some/url'); 112 | }); 113 | 114 | test('Uses given configuration without fetch', async () => { 115 | expect.assertions(1); 116 | mockFetch(url => 117 | expect(url).toBe('https://platform.adobe.io/my/api/some/url') 118 | ); 119 | const client = new BaseClient(DEFAULT_OPTS); 120 | await client.get('/some/url'); 121 | }); 122 | 123 | test('Fails with no configuration', async () => { 124 | expect.assertions(1); 125 | expect(() => new BaseClient()).toThrow('No configuration provided.'); 126 | }); 127 | }); 128 | 129 | describe('Validate API calls', () => { 130 | test('Adds custom options', async () => { 131 | expect.assertions(1); 132 | mockFetch((url, fetchOpts) => expect(fetchOpts.someOption).toBe(true)); 133 | const fetch = adobefetch.config(AUTH_ONLY_OPTS); 134 | const client = new BaseClient(fetch, { rootPath: '/my/api' }); 135 | await client.get('/some/url', true, { someOption: true }); 136 | }); 137 | 138 | test('Adds preceding slash', async () => { 139 | expect.assertions(1); 140 | mockFetch(url => 141 | expect(url).toBe('https://platform.adobe.io/my/api/some/url') 142 | ); 143 | const fetch = adobefetch.config(AUTH_ONLY_OPTS); 144 | const client = new BaseClient(fetch, { rootPath: '/my/api' }); 145 | await client.get('some/url'); 146 | }); 147 | 148 | test('Can send response object', async () => { 149 | expect.assertions(2); 150 | mockFetch(undefined, { status: 200, ok: true }); 151 | const fetch = adobefetch.config(AUTH_ONLY_OPTS); 152 | const client = new BaseClient(fetch, { rootPath: '/my/api' }); 153 | let response = await client.api('/some/url', 'GET', false); 154 | expect(response.status).toBe(200); 155 | response = await client.api('/some/url', false, false, {}); 156 | expect(response.status).toBe(200); 157 | }); 158 | 159 | test('Can send JSON', async () => { 160 | expect.assertions(2); 161 | mockFetch(undefined, { 162 | status: 200, 163 | ok: true, 164 | json: async () => { 165 | return { hello: 'world' }; 166 | } 167 | }); 168 | const fetch = adobefetch.config(AUTH_ONLY_OPTS); 169 | const client = new BaseClient(fetch, { rootPath: '/my/api' }); 170 | let response = await client.api('/some/url', 'GET', true); 171 | expect(response).toStrictEqual({ hello: 'world' }); 172 | response = await client.api('/some/url', undefined, undefined, {}); 173 | expect(response).toStrictEqual({ hello: 'world' }); 174 | }); 175 | 176 | test('Returns error when response is not ok', async () => { 177 | expect.assertions(1); 178 | mockFetch(undefined, { 179 | status: 404, 180 | statusText: 'it failed', 181 | ok: false 182 | }); 183 | const fetch = adobefetch.config(AUTH_ONLY_OPTS); 184 | const client = new BaseClient(fetch, { rootPath: '/my/api' }); 185 | await expect(client.get('/some/url')).rejects.toEqual({ 186 | error: 'it failed', 187 | status: 404 188 | }); 189 | }); 190 | 191 | test('Returns error if fetch throws error', async () => { 192 | expect.assertions(1); 193 | mockFetch(() => { 194 | throw 'Fake error'; 195 | }); 196 | const fetch = adobefetch.config(AUTH_ONLY_OPTS); 197 | const client = new BaseClient(fetch, { rootPath: '/my/api' }); 198 | await expect(client.get('/some/url')).rejects.toEqual({ 199 | error: 'Fake error', 200 | status: 0 201 | }); 202 | }); 203 | 204 | test('Returns unknown error if fetch returns an invalid response', async () => { 205 | expect.assertions(1); 206 | mockFetch(undefined, {}); 207 | const fetch = adobefetch.config(AUTH_ONLY_OPTS); 208 | const client = new BaseClient(fetch, { rootPath: '/my/api' }); 209 | await expect(client.get('/some/url')).rejects.toEqual({ 210 | error: 'Unknown error', 211 | status: 0 212 | }); 213 | }); 214 | 215 | test('Returns empty error if fetch returns an empty response', async () => { 216 | expect.assertions(1); 217 | mockFetch(undefined, () => {}); 218 | const fetch = adobefetch.config(AUTH_ONLY_OPTS); 219 | const client = new BaseClient(fetch, { rootPath: '/my/api' }); 220 | await expect(client.get('/some/url')).rejects.toEqual({ 221 | error: 'Empty response', 222 | status: 0 223 | }); 224 | }); 225 | 226 | test('Uses correct methods', async () => { 227 | expect.assertions(6); 228 | mockFetch(undefined, (url, options) => { 229 | return { 230 | ok: true, 231 | json: async () => { 232 | return { method: options.method }; 233 | } 234 | }; 235 | }); 236 | const client = new BaseClient(DEFAULT_OPTS); 237 | expect((await client.api('/some/url')).method).toBe('GET'); // Default. 238 | expect((await client.get('/some/url')).method).toBe('GET'); 239 | expect((await client.post('/some/url')).method).toBe('POST'); 240 | expect((await client.delete('/some/url')).method).toBe('DELETE'); 241 | expect((await client.patch('/some/url')).method).toBe('PATCH'); 242 | expect((await client.put('/some/url')).method).toBe('PUT'); 243 | }); 244 | 245 | test('Sends JSON in the body as string', async () => { 246 | const payload = { 247 | test: 'this', 248 | hello: { 249 | world: 1 250 | } 251 | }; 252 | expect.assertions(2); 253 | mockFetch((url, options) => { 254 | expect(options.body).toBe(JSON.stringify(payload)); 255 | expect(options.headers['content-type']).toBe('application/json'); 256 | }); 257 | const client = new BaseClient(DEFAULT_OPTS); 258 | await client.post('/some/url', payload); 259 | }); 260 | 261 | test('Sends JSON in the body with custom content type', async () => { 262 | const payload = { 263 | test: 'this', 264 | hello: { 265 | world: 1 266 | } 267 | }; 268 | expect.assertions(2); 269 | mockFetch((url, options) => { 270 | expect(options.body).toBe(JSON.stringify(payload)); 271 | expect(options.headers['content-type']).toBe('my/json'); 272 | }); 273 | const client = new BaseClient(DEFAULT_OPTS); 274 | await client.post('/some/url', payload, true, { 275 | headers: { 'content-type': 'my/json' } 276 | }); 277 | }); 278 | 279 | test('Adds cache-control header', async () => { 280 | expect.assertions(1); 281 | mockFetch((url, options) => { 282 | expect(options.headers['cache-control']).toBe('no-cache'); 283 | }); 284 | const client = new BaseClient(DEFAULT_OPTS); 285 | await client.get('/some/url', true, undefined); 286 | }); 287 | 288 | test('Adds and normalize predefined header', async () => { 289 | expect.assertions(1); 290 | mockFetch((url, options) => { 291 | expect(options.headers['some-header']).toBe('Some Value'); 292 | }); 293 | const client = new BaseClient(OPTS_WITH_HEADER); 294 | await client.get('/some/url', true, undefined); 295 | }); 296 | 297 | test('Can override predefined header', async () => { 298 | expect.assertions(1); 299 | mockFetch((url, options) => { 300 | expect(options.headers['some-header']).toBe('Some Value2'); 301 | }); 302 | const client = new BaseClient(OPTS_WITH_HEADER); 303 | await client.get('/some/url', true, { 304 | headers: { 305 | 'SOME-HEADER': 'Some Value2' 306 | } 307 | }); 308 | }); 309 | 310 | test('Can override predefined header (Headers object)', async () => { 311 | expect.assertions(1); 312 | mockFetch((url, options) => { 313 | expect(options.headers['some-header']).toBe('Some Value2'); 314 | }); 315 | const client = new BaseClient(OPTS_WITH_HEADER); 316 | const headers = new Headers(); 317 | headers.set('SOME-HEADER', 'Some Value2'); 318 | await client.get('/some/url', true, { 319 | headers: headers 320 | }); 321 | }); 322 | }); 323 | 324 | describe('Validate full URL scenarios', () => { 325 | test('Can get full URL', async () => { 326 | expect.assertions(1); 327 | mockFetch(url => 328 | expect(url).toBe('https://platform.adobe.io/my/api/some/url') 329 | ); 330 | const client = new BaseClient(DEFAULT_OPTS); 331 | await client.get('https://platform.adobe.io/my/api/some/url'); 332 | }); 333 | 334 | test('Will not accept full URL outside of endpoint', async () => { 335 | expect.assertions(1); 336 | mockFetch(url => 337 | expect(url).toBe( 338 | 'https://platform.adobe.io/my/api/https://platform.adobe.io/my2/api/some/url' 339 | ) 340 | ); 341 | const client = new BaseClient(DEFAULT_OPTS); 342 | await client.get('https://platform.adobe.io/my2/api/some/url'); 343 | }); 344 | }); 345 | 346 | describe('Validate inheritance', () => { 347 | const SubClass = class SomeClient extends BaseClient { 348 | _default() { 349 | return { 350 | name: 'sub', 351 | rootPath: '/sub/api', 352 | gateway: 'https://test.adobe.io', 353 | headers: { 354 | 'some-header': 'some-value' 355 | } 356 | }; 357 | } 358 | }; 359 | 360 | test('Override default gateway', async () => { 361 | expect.assertions(3); 362 | mockFetch((url, options) => { 363 | expect(url).toBe('https://test.adobe.io/sub/api/some/url'); 364 | expect(options.headers).toBeDefined(); 365 | expect(options.headers['some-header']).toBe('some-value'); 366 | }); 367 | const client = new SubClass(AUTH_ONLY_OPTS); 368 | await client.get('/some/url'); 369 | }); 370 | }); 371 | 372 | describe('Validate Query Param utils', () => { 373 | const client = new BaseClient(DEFAULT_OPTS); 374 | 375 | test('Adds parameter to url', () => { 376 | expect( 377 | client.addParamsToPath('/some/path', { 378 | param1: 'value1' 379 | }) 380 | ).toBe('/some/path?param1=value1'); 381 | expect( 382 | client.addParamsToPath('/some/path', { 383 | param1: 'value1', 384 | param2: 'value2' 385 | }) 386 | ).toBe('/some/path?param1=value1¶m2=value2'); 387 | }); 388 | 389 | test('Adds parameter to url and encode', () => 390 | expect( 391 | client.addParamsToPath('/some/path', { 392 | param1: 'value1', 393 | param2: 'value2@test' 394 | }) 395 | ).toBe('/some/path?param1=value1¶m2=value2%40test')); 396 | 397 | test('URL stays the same with no parameters', () => { 398 | expect(client.addParamsToPath('/some/path')).toBe('/some/path'); 399 | expect(client.addParamsToPath('/some/path?param1=value1')).toBe( 400 | '/some/path?param1=value1' 401 | ); 402 | }); 403 | 404 | test('URL stays the same with no parameters', () => { 405 | expect(client.addParamsToPath('/some/path')).toBe('/some/path'); 406 | expect(client.addParamsToPath('/some/path?param1=value1')).toBe( 407 | '/some/path?param1=value1' 408 | ); 409 | }); 410 | 411 | test('Override parameter in url', () => 412 | expect( 413 | client.addParamsToPath('/some/path?param1=value1', { 414 | param1: 'value2' 415 | }) 416 | ).toBe('/some/path?param1=value2')); 417 | }); 418 | --------------------------------------------------------------------------------