├── .gitmodules ├── docs ├── CHANGELOG.md └── readme_template.md ├── .eslintignore ├── .gitignore ├── e2e ├── .eslintrc.json ├── dev-token.json ├── jest.config.js ├── service-token.json ├── README.md └── e2e.js ├── COPYRIGHT ├── test ├── .eslintrc.json ├── setup │ ├── jest.setup.fetch.js │ └── jest.setup.js ├── jest.config.js ├── browser │ └── index.test.js ├── node │ └── index.test.js └── shared │ └── index.test.js ├── .editorconfig ├── .eslintrc.json ├── renovate.json ├── src ├── utils │ ├── config.js │ ├── SDKErrors.js │ ├── utils.js │ └── GraphQLQueryBuilder.js ├── types.js └── index.js ├── .releaserc ├── .github ├── ISSUE_TEMPLATE.md ├── workflows │ ├── ci.yml │ ├── release.yml │ ├── manual-release.yml │ └── codeql-analysis.yml ├── PULL_REQUEST_TEMPLATE.md └── CONTRIBUTING.md ├── package.json ├── CODE_OF_CONDUCT.md ├── README.md ├── LICENSE └── api-reference.md /.gitmodules: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | dist/ 3 | src/methods4docs.js 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | junit.xml 4 | .idea 5 | .env 6 | .env.development 7 | -------------------------------------------------------------------------------- /e2e/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "node/no-unpublished-require": 0 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /e2e/dev-token.json: -------------------------------------------------------------------------------- 1 | { 2 | "ok": true, 3 | "statusCode": 200, 4 | "accessToken": "abc123" 5 | } 6 | -------------------------------------------------------------------------------- /e2e/jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | testEnvironment: 'node', 3 | setupFilesAfterEnv: [ 4 | '../test/setup/jest.setup.js' 5 | ], 6 | testRegex: './e2e/e2e.js' 7 | } 8 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | © Copyright 2020-2021 Adobe. All rights reserved. 2 | 3 | Adobe holds the copyright for all the files found in this repository. 4 | 5 | See the LICENSE file for licensing information. 6 | -------------------------------------------------------------------------------- /test/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "globals": { 3 | "fixtureFile": true, 4 | "fixtureJson": true, 5 | "fakeFileSystem": true, 6 | "fetch": true 7 | }, 8 | "rules": { 9 | "node/no-unpublished-require": 0 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_style = space 7 | trim_trailing_whitespace = true 8 | 9 | [*.{js,json,scss,html,md}] 10 | indent_size = 2 11 | insert_final_newline = true 12 | 13 | [*.md] 14 | trim_trailing_whitespace = false 15 | indent_size = 4 16 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["@adobe/eslint-config-aio-lib-config"], 3 | "rules": { 4 | "jsdoc/no-undefined-types": 0, 5 | "jsdoc/no-defaults": 0, 6 | "jsdoc/check-tag-names": [ 7 | "error", 8 | { 9 | "definedTags": ["jest-environment"] 10 | } 11 | ] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:recommended" 5 | ], 6 | "packageRules": [ 7 | { 8 | "matchUpdateTypes": ["minor", "patch", "pin", "digest"], 9 | "automerge": true 10 | }, 11 | { 12 | "matchDepTypes": ["devDependencies"], 13 | "automerge": true 14 | } 15 | ], 16 | "platformAutomerge": true 17 | } 18 | -------------------------------------------------------------------------------- /src/utils/config.js: -------------------------------------------------------------------------------- 1 | const AEM_GRAPHQL_ACTIONS = { 2 | persist: 'graphql/persist.json', 3 | execute: 'graphql/execute.json', 4 | list: 'graphql/list.json', 5 | endpoint: 'content/graphql/global/endpoint.json', 6 | serviceURL: '/' 7 | } 8 | 9 | const AEM_GRAPHQL_TYPES = { 10 | BY_PATH: 'ByPath', 11 | LIST: 'List', 12 | PAGINATED: 'Paginated' 13 | } 14 | 15 | module.exports = { 16 | AEM_GRAPHQL_ACTIONS, 17 | AEM_GRAPHQL_TYPES 18 | } 19 | -------------------------------------------------------------------------------- /.releaserc: -------------------------------------------------------------------------------- 1 | { 2 | "branches": ["main"], 3 | "plugins": [ 4 | "@semantic-release/commit-analyzer", 5 | "@semantic-release/release-notes-generator", 6 | [ 7 | "@semantic-release/changelog", 8 | { 9 | "changelogFile": "docs/CHANGELOG.md" 10 | } 11 | ], 12 | "@semantic-release/npm", 13 | [ 14 | "@semantic-release/git", 15 | { 16 | "assets": ["docs/CHANGELOG.md", "package.json"] 17 | } 18 | ] 19 | ] 20 | } -------------------------------------------------------------------------------- /e2e/service-token.json: -------------------------------------------------------------------------------- 1 | { 2 | "ok": true, 3 | "integration": { 4 | "imsEndpoint": "example.adobelogin.com", 5 | "metascopes": "ent_aem_cloud_sdk,ent_cloudmgr_sdk", 6 | "technicalAccount": { 7 | "clientId": "cm-p123-e1234", 8 | "clientSecret": "1REDACTED2" 9 | }, 10 | "email": "abcd@techacct.adobe.com", 11 | "id": "ABCDAE10A495E8C@techacct.adobe.com", 12 | "org": "1234@AdobeOrg", 13 | "privateKey": "-----BEGIN RSA PRIVATE KEY----------END RSA PRIVATE KEY-----\r\n", 14 | "publicKey": "-----BEGIN CERTIFICATE---------END CERTIFICATE-----\r\n" 15 | }, 16 | "statusCode": 200 17 | } 18 | -------------------------------------------------------------------------------- /test/setup/jest.setup.fetch.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 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 | Unless required by applicable law or agreed to in writing, software distributed under 7 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 8 | OF ANY KIND, either express or implied. See the License for the specific language 9 | governing permissions and limitations under the License. 10 | */ 11 | 12 | require('jest-fetch-mock').enableMocks() 13 | -------------------------------------------------------------------------------- /docs/readme_template.md: -------------------------------------------------------------------------------- 1 | 12 | # AEM HEADLESS SDK API Reference 13 | 14 | {{>main-index~}}{{>all-docs~}} -------------------------------------------------------------------------------- /.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 17 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [ '**' ] 6 | pull_request: 7 | branches: [ $default-branch ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ${{ matrix.os }} 13 | 14 | strategy: 15 | matrix: 16 | os: [ubuntu-latest] 17 | node-version: [20.x] 18 | 19 | steps: 20 | - name: Checkout 21 | uses: actions/checkout@v4 22 | - name: Setup Node.js ${{ matrix.node-version }} 23 | uses: actions/setup-node@v4 24 | with: 25 | node-version: ${{ matrix.node-version }} 26 | - name: Install dependencies 27 | run: npm ci 28 | - name: Build Library 29 | run: npm run build --if-present 30 | - name: Run Tests 31 | run: npm test --if-present 32 | -------------------------------------------------------------------------------- /test/setup/jest.setup.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Adobe Inc. 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 { stdout } = require('stdout-stderr') 14 | 15 | process.env.CI = true 16 | 17 | jest.setTimeout(30000) 18 | jest.useFakeTimers() 19 | 20 | // trap console log 21 | beforeEach(() => { stdout.start() }) 22 | afterEach(() => { stdout.stop() }) 23 | -------------------------------------------------------------------------------- /test/jest.config.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 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 | Unless required by applicable law or agreed to in writing, software distributed under 7 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 8 | OF ANY KIND, either express or implied. See the License for the specific language 9 | governing permissions and limitations under the License. 10 | */ 11 | 12 | module.exports = { 13 | testEnvironment: 'jsdom', 14 | rootDir: '..', 15 | collectCoverage: true, 16 | collectCoverageFrom: [ 17 | '/src/**/*.js' 18 | ], 19 | coverageThreshold: { 20 | global: { 21 | branches: 10, 22 | lines: 10, 23 | statements: 10 24 | } 25 | }, 26 | reporters: [ 27 | 'default', 28 | 'jest-junit' 29 | ], 30 | setupFilesAfterEnv: [ 31 | '/test/setup/jest.setup.js', 32 | '/test/setup/jest.setup.fetch.js' 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | release: 10 | name: Test, Build and Release 11 | runs-on: ${{ matrix.os }} 12 | strategy: 13 | matrix: 14 | os: [ ubuntu-latest ] 15 | node-version: [ 20.x ] 16 | 17 | steps: 18 | - name: Checkout 19 | uses: actions/checkout@v4 20 | - name: Setup Node.js 21 | uses: actions/setup-node@v4 22 | with: 23 | node-version: ${{ matrix['node-version'] }} 24 | - name: Install dependencies 25 | run: npm ci 26 | - name: Build Library 27 | run: npm run build --if-present 28 | - name: Run Tests 29 | run: npm test --if-present 30 | - name: Release 31 | uses: cycjimmy/semantic-release-action@v4 32 | with: 33 | dry_run: true 34 | extra_plugins: | 35 | @semantic-release/changelog 36 | @semantic-release/git 37 | env: 38 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 39 | NPM_TOKEN: ${{ secrets.ADOBE_BOT_NPM_TOKEN }} 40 | GIT_AUTHOR_NAME: github-actions 41 | GIT_AUTHOR_EMAIL: github-actions@github.com 42 | GIT_COMMITTER_NAME: github-actions 43 | GIT_COMMITTER_EMAIL: github-actions@github.com 44 | CI: true 45 | -------------------------------------------------------------------------------- /e2e/README.md: -------------------------------------------------------------------------------- 1 | # E2E Tests 2 | 3 | ## Requirements 4 | 5 | To run the e2e test you'll need these env variables set: 6 | 1. `AEM_HOST_URI` 7 | 2. `AEM_GRAPHQL_ENDPOINT` (if different from default `content/graphql/endpoint.gql`) 8 | 3. `AEM_TOKEN` (or `AEM_USER` and `AEM_PASS`) 9 | 10 | ### Example 11 | ```bash 12 | AEM_HOST_URI=http://localhost:4502 13 | AEM_GRAPHQL_ENDPOINT=/content/cq:graphql/wknd-shared/endpoint.json 14 | AEM_USER=admin 15 | AEM_PASS=admin 16 | ``` 17 | ## Run 18 | 19 | `npm run e2e` 20 | 21 | ## Test overview 22 | 23 | The tests cover: 24 | 25 | 1. Malformed required params 26 | 2. All APIs 27 | - persistQuery 28 | - listPersistedQueries 29 | - runPersistedQuery 30 | - runQuery 31 | 32 | ## Local AEM setup 33 | 34 | 1. Navigate to the [Software Distribution Portal](https://experience.adobe.com/#/downloads/content/software-distribution/en/aemcloud.html?fulltext=AEM*+SDK*&orderby=%40jcr%3Acontent%2Fjcr%3AlastModified&orderby.sort=desc&layout=list&p.offset=0&p.limit=1) > AEM as a Cloud Service and download the latest version of the AEM SDK. 35 | 2. Start AEM 36 | ``` 37 | java -jar aem-author-p4502.jar 38 | ``` 39 | 3. Download the latest compiled AEM Package for WKND Site: [aem-guides-wknd.all-x.x.x.zip](https://github.com/adobe/aem-guides-wknd/releases/latest). 40 | 4. Install downloaded Demo Content package 41 | 5. Configure ENV variables 42 | 6. Run e2e test 43 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "4.0.0", 3 | "bugs": { 4 | "url": "https://github.com/adobe/aem-headless-client-js/issues" 5 | }, 6 | "deprecated": false, 7 | "description": "AEM Headless SDK Client", 8 | "homepage": "https://github.com/adobe/aem-headless-client-js", 9 | "license": "Apache-2.0", 10 | "main": "src/index.js", 11 | "name": "@adobe/aem-headless-client-js", 12 | "repository": "https://github.com/adobe/aem-headless-client-js", 13 | "scripts": { 14 | "docs": "jsdoc2md --no-gfm -t ./docs/readme_template.md src/types.js src/index.js > api-reference.md", 15 | "lint": "eslint src test", 16 | "unit-tests": "jest --config test/jest.config.js --maxWorkers=2 --verbose", 17 | "test": "npm run lint && npm run unit-tests", 18 | "e2e": "jest --config e2e/jest.config.js" 19 | }, 20 | "publishConfig": { 21 | "access": "public" 22 | }, 23 | "engines": { 24 | "node": ">=20.0.0" 25 | }, 26 | "files": [ 27 | "/src", 28 | "api-reference.md", 29 | "CODE_OF_CONDUCT.md", 30 | "COPYRIGHT" 31 | ], 32 | "dependencies": { 33 | "@adobe/aio-lib-core-errors": "4.0.1" 34 | }, 35 | "devDependencies": { 36 | "@adobe/eslint-config-aio-lib-config": "4.0.0", 37 | "cross-fetch": "4.1.0", 38 | "dotenv": "17.2.3", 39 | "jest": "30.2.0", 40 | "jest-environment-jsdom": "30.2.0", 41 | "jest-fetch-mock": "3.0.3", 42 | "jest-junit": "16.0.0", 43 | "jsdoc-to-markdown": "9.1.3", 44 | "stdout-stderr": "0.1.13" 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/utils/SDKErrors.js: -------------------------------------------------------------------------------- 1 | const { ErrorWrapper, createUpdater } = require('@adobe/aio-lib-core-errors').AioCoreSDKErrorWrapper 2 | 3 | const codes = {} 4 | const messages = new Map() 5 | 6 | /** 7 | * Create an Updater for the Error wrapper 8 | * 9 | * @ignore 10 | */ 11 | const Updater = createUpdater( 12 | // object that stores the error classes (to be exported) 13 | codes, 14 | // Map that stores the error strings (to be exported) 15 | messages 16 | ) 17 | 18 | /** 19 | * Provides a wrapper to easily create classes of a certain name, and values 20 | * 21 | * @ignore 22 | */ 23 | const E = ErrorWrapper( 24 | // The class name for your SDK Error. Your Error objects will be these objects 25 | 'AEMHeadlessError', 26 | // The name of your SDK. This will be a property in your Error objects 27 | 'AEMHeadless', 28 | // the object returned from the CreateUpdater call above 29 | Updater 30 | // the base class that your Error class is extending. AioCoreSDKError is the default 31 | /* , AioCoreSDKError */ 32 | ) 33 | 34 | module.exports = { 35 | codes, 36 | messages 37 | } 38 | 39 | // Commons errors 40 | E('REQUEST_ERROR', 'General Request error: %s.') 41 | E('RESPONSE_ERROR', 'There was a problem parsing response data: %s.') 42 | E('API_ERROR', 'There was a problem with your API call: %s.') 43 | E('INVALID_PARAM', 'There was a problem with required params: %s.') 44 | // NodeJS Errors 45 | E('AUTH_FILE_READ_ERROR', 'There was a problem reading auth file: %s.') 46 | E('AUTH_FILE_PARSE_ERROR', 'There was a problem parsing auth file: %s.') 47 | E('EXCHANGE_TOKEN_ERROR', 'There was a problem fetching exchange token: %s.') 48 | -------------------------------------------------------------------------------- /.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. 46 | -------------------------------------------------------------------------------- /test/browser/index.test.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @jest-environment jsdom 3 | */ 4 | 5 | /* 6 | Copyright 2021 Adobe. All rights reserved. 7 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 8 | you may not use this file except in compliance with the License. You may obtain a copy 9 | of the License at http://www.apache.org/licenses/LICENSE-2.0 10 | Unless required by applicable law or agreed to in writing, software distributed under 11 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 12 | OF ANY KIND, either express or implied. See the License for the specific language 13 | governing permissions and limitations under the License. 14 | */ 15 | 16 | const AEMHeadless = require('../../src') 17 | const { AEM_GRAPHQL_ACTIONS } = require('../../src/utils/config') 18 | // ///////////////////////////////////////////// 19 | let sdk = {} 20 | 21 | test('SDK Constructor: string as a constructor param is used as serviceURL', () => { 22 | sdk = new AEMHeadless('test') 23 | expect(sdk).toHaveProperty('serviceURL', 'test/') 24 | }) 25 | 26 | test('SDK Constructor: Fetch is not required param "config.fetch" in Browser env', () => { 27 | const config = {} 28 | sdk = new AEMHeadless(config) 29 | expect(sdk).toHaveProperty('fetch') 30 | }) 31 | 32 | test('SDK Constructor: if no config is provided default params are used', () => { 33 | const config = {} 34 | sdk = new AEMHeadless(config) 35 | expect(sdk).toHaveProperty('serviceURL', AEM_GRAPHQL_ACTIONS.serviceURL) 36 | expect(sdk).toHaveProperty('endpoint', AEM_GRAPHQL_ACTIONS.endpoint) 37 | expect(sdk).toHaveProperty('fetch') 38 | }) 39 | 40 | test('SDK Constructor: all custom params should match', () => { 41 | const config = { 42 | serviceURL: 'test/', 43 | endpoint: '/test', 44 | auth: 'test', 45 | headers: { test1: 'test1', test2: 'test2' } 46 | } 47 | sdk = new AEMHeadless(config) 48 | expect(sdk).toHaveProperty('serviceURL', 'test/') 49 | expect(sdk).toHaveProperty('endpoint', 'test') 50 | expect(sdk).toHaveProperty('auth', 'test') 51 | expect(sdk).toHaveProperty('headers', { test1: 'test1', test2: 'test2' }) 52 | }) 53 | 54 | test('SDK Constructor: auth is optional', () => { 55 | const config = {} 56 | sdk = new AEMHeadless(config) 57 | expect(sdk).toHaveProperty('auth', undefined) 58 | }) 59 | -------------------------------------------------------------------------------- /test/node/index.test.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @jest-environment node 3 | */ 4 | 5 | /* 6 | Copyright 2021 Adobe. All rights reserved. 7 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 8 | you may not use this file except in compliance with the License. You may obtain a copy 9 | of the License at http://www.apache.org/licenses/LICENSE-2.0 10 | Unless required by applicable law or agreed to in writing, software distributed under 11 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 12 | OF ANY KIND, either express or implied. See the License for the specific language 13 | governing permissions and limitations under the License. 14 | */ 15 | 16 | const { AEMHeadless, ErrorCodes } = require('../../src') 17 | const { AEM_GRAPHQL_ACTIONS } = require('../../src/utils/config') 18 | // ///////////////////////////////////////////// 19 | let sdk = {} 20 | 21 | test('SDK Constructor: string as a constructor param fails in NodeJS env', () => { 22 | const config = 'http://localhost' 23 | expect(() => new AEMHeadless(config)).toThrow(ErrorCodes.REQUIRED_PARAMS) 24 | }) 25 | 26 | test('SDK Constructor: Fetch is a required param "config.fetch" in NodeJS env', () => { 27 | const config = {} 28 | expect(() => new AEMHeadless(config)).toThrow('Required param missing: config.fetch') 29 | }) 30 | 31 | test('SDK Constructor: if no additional config is provided default params are used', () => { 32 | const config = { 33 | fetch 34 | } 35 | sdk = new AEMHeadless(config) 36 | expect(sdk).toHaveProperty('serviceURL', AEM_GRAPHQL_ACTIONS.serviceURL) 37 | expect(sdk).toHaveProperty('endpoint', AEM_GRAPHQL_ACTIONS.endpoint) 38 | expect(sdk).toHaveProperty('fetch', fetch) 39 | }) 40 | 41 | test('SDK Constructor: all custom params should match', () => { 42 | const config = { 43 | serviceURL: 'test', 44 | endpoint: 'test', 45 | auth: 'test', 46 | fetch 47 | } 48 | sdk = new AEMHeadless(config) 49 | expect(sdk).toHaveProperty('serviceURL') 50 | expect(sdk).toHaveProperty('endpoint') 51 | }) 52 | 53 | test('SDK Constructor: headers is optional', () => { 54 | const config = { 55 | fetch 56 | } 57 | sdk = new AEMHeadless(config) 58 | expect(sdk).toHaveProperty('headers', undefined) 59 | }) 60 | 61 | test('SDK Constructor: auth is optional', () => { 62 | const config = { 63 | fetch 64 | } 65 | sdk = new AEMHeadless(config) 66 | expect(sdk).toHaveProperty('auth', undefined) 67 | }) 68 | -------------------------------------------------------------------------------- /.github/workflows/manual-release.yml: -------------------------------------------------------------------------------- 1 | name: Manual Release 2 | on: 3 | workflow_dispatch: 4 | inputs: 5 | version: 6 | description: 'Version' 7 | type: choice 8 | required: true 9 | default: fix 10 | options: 11 | - fix 12 | - feat 13 | - BREAKING CHANGE 14 | dryRun: 15 | description: 'DryRun' 16 | type: boolean 17 | default: true 18 | # ENV and Config 19 | env: 20 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 21 | NPM_TOKEN: ${{ secrets.ADOBE_BOT_NPM_TOKEN }} 22 | GIT_AUTHOR_NAME: github-actions 23 | GIT_AUTHOR_EMAIL: github-actions@github.com 24 | GIT_COMMITTER_NAME: github-actions 25 | GIT_COMMITTER_EMAIL: github-actions@github.com 26 | CI: true 27 | CONFIG_NODE_VERSION: '["20.x"]' 28 | CONFIG_OS: '["ubuntu-latest"]' 29 | # Main Job 30 | jobs: 31 | config: 32 | runs-on: ubuntu-latest 33 | outputs: 34 | NODE_VERSION: ${{ steps.set-config.outputs.CONFIG_NODE_VERSION }} 35 | OS: ${{ steps.set-config.outputs.CONFIG_OS }} 36 | steps: 37 | - id: set-config 38 | run: | 39 | echo "CONFIG_NODE_VERSION=${{ toJSON(env.CONFIG_NODE_VERSION) }}" >> $GITHUB_OUTPUT 40 | echo "CONFIG_OS=${{ toJSON(env.CONFIG_OS) }}" >> $GITHUB_OUTPUT 41 | release: 42 | name: Test, Build and force Release 43 | needs: config 44 | 45 | runs-on: ${{ matrix.OS }} 46 | strategy: 47 | matrix: 48 | OS: ${{ fromJSON(needs.config.outputs.OS) }} 49 | NODE_VERSION: ${{ fromJSON(needs.config.outputs.NODE_VERSION) }} 50 | 51 | steps: 52 | - name: Checkout repo 53 | uses: actions/checkout@v4 54 | - name: Setup Node.js ${{ matrix.NODE_VERSION }} 55 | uses: actions/setup-node@v4 56 | with: 57 | node-version: ${{ matrix.NODE_VERSION }} 58 | - name: Commit trigger 59 | run: | 60 | git commit --allow-empty -m "${{ github.event.inputs.version }}: Trigger Manual Release 61 | 62 | ${{ github.event.inputs.version }}:Forced Manual Release without code changes" 63 | - name: Install dependencies 64 | run: npm ci 65 | - name: Build Library 66 | run: npm run build --if-present 67 | - name: Run Tests 68 | run: npm test --if-present 69 | - name: Publish npm package 70 | uses: cycjimmy/semantic-release-action@v4 71 | with: 72 | dry_run: ${{ github.event.inputs.dryRun == 'true' }} 73 | extra_plugins: | 74 | @semantic-release/changelog 75 | @semantic-release/git 76 | -------------------------------------------------------------------------------- /src/types.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Query string type 3 | * 4 | * @private 5 | * @typedef {string} QueryString 6 | */ 7 | 8 | /** 9 | * GraphQL Model type 10 | * 11 | * @typedef {object} Model 12 | * @property {any} * - model properties 13 | */ 14 | 15 | /** 16 | * @typedef {object} ModelResult 17 | * @property {Model} item - response item 18 | */ 19 | 20 | /** 21 | * @typedef {object} ModelResults 22 | * @property {Model[]} items - response items 23 | */ 24 | 25 | /** 26 | * @typedef {object} ModelEdge 27 | * @property {string} cursor - item cursor 28 | * @property {Model} node - item node 29 | */ 30 | 31 | /** 32 | * @typedef {object} PageInfo 33 | * @property {string} endCursor - endCursor 34 | * @property {boolean} hasNextPage - hasNextPage 35 | * @property {boolean} hasPreviousPage - hasPreviousPage 36 | * @property {string} startCursor - startCursor 37 | */ 38 | 39 | /** 40 | * @typedef {object} ModelConnection 41 | * @property {ModelEdge[]} edges - edges 42 | * @property {PageInfo} pageInfo - pageInfo 43 | */ 44 | 45 | /** 46 | * @typedef {object} ModelByPathArgs 47 | * @property {string} _path - contentFragment path 48 | * @property {string} variation - contentFragment variation 49 | */ 50 | 51 | /** 52 | * @typedef {object} ModelListArgs 53 | * @property {string} [_locale] - contentFragment locale 54 | * @property {string} [variation] - contentFragment variation 55 | * @property {object} [filter] - list filter options 56 | * @property {string} [sort] - list sort options 57 | * @property {number} [offset] - list offset 58 | * @property {number} [limit] - list limit 59 | */ 60 | 61 | /** 62 | * @typedef {object} ModelPaginatedArgs 63 | * @property {string} [_locale] - contentFragment locale 64 | * @property {string} [variation] - contentFragment variation 65 | * @property {object} [filter] - list filter options 66 | * @property {string} [sort] - list sort options 67 | * @property {number} [first] - number of list items 68 | * @property {string} [after] - list starting cursor 69 | */ 70 | 71 | /** 72 | * @typedef {ModelByPathArgs|ModelListArgs|ModelPaginatedArgs} ModelArgs 73 | * @property {any} * - placeholder property 74 | */ 75 | 76 | /** 77 | * @typedef {object} QueryBuilderResult 78 | * @property {string} type - Query type 79 | * @property {QueryString} query - Query string 80 | */ 81 | 82 | /** 83 | * @typedef {object} ModelConfig 84 | * @property {number} [pageSize=10] - page size 85 | * @property {string|number} [after] - starting cursor or offset 86 | * @property {boolean} [useLimitOffset=false] - use offset pagination 87 | */ 88 | 89 | module.exports = {} 90 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ main ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ main ] 20 | schedule: 21 | - cron: '20 12 * * 0' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | 28 | strategy: 29 | fail-fast: false 30 | matrix: 31 | language: [ 'javascript' ] 32 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 33 | # Learn more: 34 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 35 | 36 | steps: 37 | - name: Checkout repository 38 | uses: actions/checkout@v4 39 | 40 | # Initializes the CodeQL tools for scanning. 41 | - name: Initialize CodeQL 42 | uses: github/codeql-action/init@v3 43 | with: 44 | languages: ${{ matrix.language }} 45 | # If you wish to specify custom queries, you can do so here or in a config file. 46 | # By default, queries listed here will override any specified in a config file. 47 | # Prefix the list here with "+" to use these queries and those in the config file. 48 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 49 | 50 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 51 | # If this step fails, then you should remove it and run the build manually (see below) 52 | - name: Autobuild 53 | uses: github/codeql-action/autobuild@v3 54 | 55 | # ℹ️ Command-line programs to run using the OS shell. 56 | # 📚 https://git.io/JvXDl 57 | 58 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 59 | # and modify them (or add more) to build your code if your project 60 | # uses a compiled language 61 | 62 | #- run: | 63 | # make bootstrap 64 | # make release 65 | 66 | - name: Perform CodeQL Analysis 67 | uses: github/codeql-action/analyze@v3 68 | -------------------------------------------------------------------------------- /.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 | ## Release 14 | - based on Angular Commit Message Conventions in commits - 15 | https://github.com/angular/angular/blob/master/CONTRIBUTING.md#commit-message-header 16 | - Commit message format is used to build: 17 | * Release notes 18 | * Changelog updates 19 | * NPM package semver 20 | 21 | ## Commit message Convention 22 | 23 | ``` 24 | (): 25 | │ │ │ 26 | │ │ └─⫸ Summary in present tense. Not capitalized. No period at the end. 27 | │ │ 28 | │ └─⫸ Commit Scope (optional): project|based|list 29 | │ 30 | └─⫸ Commit Type: build|ci|docs|feat|fix|perf|refactor|test 31 | ``` 32 | 33 | 34 | ### Major Version Release: 35 | 36 | In order to trigger Major Version upgrade, `BREAKING CHANGE:` needs to be in the footer of a commit message: 37 | 38 | ``` 39 | (): 40 | 41 | BREAKING CHANGE: 42 | ``` 43 | 44 | ## Have A Question? 45 | 46 | Start by filing an issue. The existing committers on this project work to reach 47 | consensus around project direction and issue solutions within issue threads 48 | (when appropriate). 49 | 50 | ## Contributor License Agreement 51 | 52 | All third-party contributions to this project must be accompanied by a signed contributor 53 | license agreement. This gives Adobe permission to redistribute your contributions 54 | as part of the project. [Sign our CLA](http://opensource.adobe.com/cla.html). You 55 | only need to submit an Adobe CLA one time, so if you have submitted one previously, 56 | you are good to go! 57 | 58 | ## Code Reviews 59 | 60 | All submissions should come in the form of pull requests and need to be reviewed 61 | by project committers. Read [GitHub's pull request documentation](https://help.github.com/articles/about-pull-requests/) 62 | for more information on sending pull requests. 63 | 64 | Lastly, please follow the [pull request template](PULL_REQUEST_TEMPLATE.md) when 65 | submitting a pull request! 66 | 67 | ## From Contributor To Committer 68 | 69 | We love contributions from our community! If you'd like to go a step beyond contributor 70 | and become a committer with full write access and a say in the project, you must 71 | be invited to the project. The existing committers employ an internal nomination 72 | process that must reach lazy consensus (silence is approval) before invitations 73 | are issued. If you feel you are qualified and want to get more deeply involved, 74 | feel free to reach out to existing committers to have a conversation about that. 75 | 76 | ## Security Issues 77 | 78 | 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) 79 | -------------------------------------------------------------------------------- /src/utils/utils.js: -------------------------------------------------------------------------------- 1 | const { INVALID_PARAM } = require('./SDKErrors').codes 2 | 3 | /** 4 | * simple string to base64 implementation 5 | * 6 | * @private 7 | * @param {string} str 8 | */ 9 | const __str2base64 = (str) => { 10 | if (typeof btoa === 'function') { 11 | return btoa(str) 12 | } else { 13 | return Buffer.from(str, 'utf8').toString('base64') 14 | } 15 | } 16 | 17 | /** 18 | * Returns valid url. 19 | * 20 | * @private 21 | * @param {string} domain 22 | * @param {string} path 23 | * @returns {string} valid url 24 | */ 25 | const __getUrl = (domain, path) => { 26 | return `${domain}${path}` 27 | } 28 | 29 | /** 30 | * Removes first / in a path 31 | * 32 | * @private 33 | * @param {string} path 34 | * @returns {string} path 35 | */ 36 | const __getPath = (path) => { 37 | return path[0] === '/' ? path.substring(1) : path 38 | } 39 | 40 | /** 41 | * Add last / in domain 42 | * 43 | * @private 44 | * @param {string} domain 45 | * @returns {string} valid domain 46 | */ 47 | const __getDomain = (domain) => { 48 | return domain[domain.length - 1] === '/' ? domain : `${domain}/` 49 | } 50 | 51 | /** 52 | * Check valid url or absolute path 53 | * 54 | * @private 55 | * @param {string} url 56 | * @returns void 57 | */ 58 | const __validateUrl = (url) => { 59 | const fullUrl = url[0] === '/' ? `https://domain${url}` : url 60 | 61 | try { 62 | new URL(fullUrl) // eslint-disable-line 63 | } catch (e) { 64 | throw new INVALID_PARAM({ 65 | messageValues: `Invalid URL/path: ${url}` 66 | }) 67 | } 68 | } 69 | 70 | /** 71 | * get Browser Fetch instance 72 | * 73 | * @private 74 | * @returns {object} fetch instance 75 | */ 76 | const __getBrowserFetch = () => { 77 | if (typeof window !== 'undefined') { 78 | return window.fetch.bind(window) 79 | } 80 | 81 | if (typeof self !== 'undefined') { 82 | return self.fetch.bind(self) // eslint-disable-line 83 | } 84 | 85 | return null 86 | } 87 | 88 | /** 89 | * get Fetch instance 90 | * 91 | * @private 92 | * @param {object} [fetch] 93 | * @returns {object} fetch instance 94 | */ 95 | const __getFetch = (fetch) => { 96 | if (!fetch) { 97 | const browserFetch = __getBrowserFetch() 98 | if (!browserFetch) { 99 | throw new INVALID_PARAM({ 100 | messageValues: 'Required param missing: config.fetch' 101 | }) 102 | } 103 | 104 | return browserFetch 105 | } 106 | 107 | return fetch 108 | } 109 | 110 | /** 111 | * Returns Authorization Header value. 112 | * 113 | * @private 114 | * @param {string|array} auth - Bearer token string or [user,pass] pair array 115 | * @returns {string} Authorization Header value 116 | */ 117 | const __getAuthHeader = (auth) => { 118 | let authType = 'Bearer' 119 | let authToken = auth 120 | // If auth is user, password` pair 121 | if (Array.isArray(auth) && auth[0] && auth[1]) { 122 | authType = 'Basic' 123 | authToken = __str2base64(`${auth[0]}:${auth[1]}`) 124 | } 125 | 126 | return `${authType} ${authToken}` 127 | } 128 | 129 | module.exports = { 130 | __getUrl, 131 | __getPath, 132 | __getDomain, 133 | __validateUrl, 134 | __getFetch, 135 | __getAuthHeader 136 | } 137 | -------------------------------------------------------------------------------- /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 [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: https://contributor-covenant.org 74 | [version]: https://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /e2e/e2e.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 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 | Unless required by applicable law or agreed to in writing, software distributed under 7 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 8 | OF ANY KIND, either express or implied. See the License for the specific language 9 | governing permissions and limitations under the License. 10 | */ 11 | 12 | const path = require('path') 13 | const fetch = require('cross-fetch') 14 | 15 | // load .env values in the e2e folder, if any 16 | require('dotenv').config({ path: path.join(__dirname, '.env') }) 17 | 18 | const AEMHeadless = require('../src') 19 | 20 | const { AEM_TOKEN, AEM_USER = 'admin', AEM_PASS = 'admin', AEM_HOST_URI = 'http://localhost:4502', AEM_GRAPHQL_ENDPOINT = 'content/_cq_graphql/wknd-shared/endpoint.json' } = process.env 21 | 22 | const queryString = ` 23 | { 24 | adventureList { 25 | items { 26 | _path 27 | } 28 | } 29 | } 30 | ` 31 | let sdk = {} 32 | const persistedName = 'wknd-shared/persist-query-name' 33 | const existingQueryName = 'wknd-shared/adventures-all' 34 | 35 | beforeEach(() => { 36 | sdk = new AEMHeadless({ 37 | serviceURL: AEM_HOST_URI, 38 | endpoint: AEM_GRAPHQL_ENDPOINT, 39 | auth: AEM_TOKEN || [AEM_USER, AEM_PASS], 40 | fetch 41 | }) 42 | }) 43 | 44 | test('e2e test sdk valid params', () => { 45 | expect(sdk).toHaveProperty('serviceURL') 46 | expect(sdk).toHaveProperty('endpoint') 47 | }) 48 | 49 | test('e2e test sdk missing params', () => { 50 | // check success response 51 | const config = { fetch } 52 | sdk = new AEMHeadless(config) 53 | expect(sdk).toHaveProperty('serviceURL') 54 | expect(sdk).toHaveProperty('endpoint') 55 | }) 56 | 57 | test('e2e test sdk missing param serviceURL', () => { 58 | // check success response 59 | const config = { endpoint: 'test', fetch } 60 | sdk = new AEMHeadless(config) 61 | expect(sdk).toHaveProperty('serviceURL') 62 | expect(sdk).toHaveProperty('endpoint') 63 | }) 64 | let uniqueName 65 | test('e2e test persistQuery API Success', () => { 66 | // check success response 67 | uniqueName = `${persistedName}-${Date.now()}` 68 | const promise = sdk.persistQuery(queryString, uniqueName) 69 | return expect(promise).resolves.toBeTruthy() 70 | }) 71 | 72 | test('e2e test persistQuery API Error', () => { 73 | // check error response 74 | const promise = sdk.persistQuery(queryString, uniqueName) 75 | return expect(promise).rejects.toThrow() 76 | }) 77 | 78 | test('e2e test listPersistedQueries API Success', () => { 79 | const promise = sdk.listPersistedQueries() 80 | return expect(promise).resolves.toBeTruthy() 81 | }) 82 | 83 | test('e2e test runQuery API Success', () => { 84 | // check success response 85 | const promise = sdk.runQuery(queryString) 86 | return expect(promise).resolves.toBeTruthy() 87 | }) 88 | 89 | test('e2e test runQuery API Error', () => { 90 | // check error response 91 | const promise = sdk.runQuery() 92 | return expect(promise).rejects.toThrow() 93 | }) 94 | 95 | test('e2e test runPersistedQuery API Success', () => { 96 | // check success response 97 | const promise = sdk.runPersistedQuery(existingQueryName) 98 | return expect(promise).resolves.toBeTruthy() 99 | }) 100 | 101 | test('e2e test runPersistedQuery API Error', () => { 102 | // check error response 103 | const promise = sdk.runPersistedQuery('/test') 104 | return expect(promise).rejects.toThrow() 105 | }) 106 | -------------------------------------------------------------------------------- /src/utils/GraphQLQueryBuilder.js: -------------------------------------------------------------------------------- 1 | require('../types') // eslint-disable-line 2 | const { AEM_GRAPHQL_TYPES } = require('./config') 3 | 4 | /** 5 | * 6 | * @private 7 | * @param {object} obj - object representing query arguments 8 | * @returns {string} - query args as a string 9 | */ 10 | function objToStringArgs (obj) { 11 | const str = JSON.stringify(obj).replace(/"([^"]+)":/g, '$1:') 12 | return str.substring(1, str.length - 1) 13 | } 14 | 15 | /** 16 | * Returns a Query for model by path 17 | * 18 | * @private 19 | * @param {string} model - contentFragment Model Name 20 | * @param {string} fields - The query string for item fields. 21 | * @param {ModelByPathArgs} args - Query arguments 22 | * @returns {QueryBuilderResult} 23 | */ 24 | const __modelByPath = (model, fields, args) => { 25 | if (!args || !args._path) { 26 | throw new Error('Missing required param "_path"') 27 | } 28 | const type = AEM_GRAPHQL_TYPES.BY_PATH 29 | const query = `{ 30 | ${model}${type}( 31 | ${objToStringArgs(args)} 32 | ) { 33 | item ${fields} 34 | } 35 | }` 36 | 37 | return { 38 | type, 39 | query 40 | } 41 | } 42 | 43 | /** 44 | * Returns a Query for model list 45 | * 46 | * @private 47 | * @param {string} model - contentFragment Model Name 48 | * @param {string} fields - The query string for item fields. 49 | * @param {ModelListArgs} [args={}] - Query arguments 50 | * @returns {QueryBuilderResult} 51 | */ 52 | const __modelList = (model, fields, args = {}) => { 53 | const type = AEM_GRAPHQL_TYPES.LIST 54 | const query = `{ 55 | ${model}${type}( 56 | ${objToStringArgs(args)} 57 | ) { 58 | items ${fields} 59 | } 60 | }` 61 | 62 | return { 63 | type, 64 | query 65 | } 66 | } 67 | 68 | /** 69 | * Returns a Query for model list 70 | * 71 | * @private 72 | * @param {string} model - contentFragment Model Name 73 | * @param {string} fields - The query string for item fields. 74 | * @param {ModelPaginatedArgs} [args={}] - Query arguments 75 | * @returns {QueryBuilderResult} 76 | */ 77 | const __modelPaginated = (model, fields, args = {}) => { 78 | const type = AEM_GRAPHQL_TYPES.PAGINATED 79 | const query = `{ 80 | ${model}${type}( 81 | ${objToStringArgs(args)} 82 | ) { 83 | pageInfo { 84 | startCursor 85 | endCursor 86 | hasNextPage 87 | hasPreviousPage 88 | } 89 | edges { 90 | node ${fields} 91 | cursor 92 | } 93 | } 94 | }` 95 | 96 | return { 97 | type, 98 | query 99 | } 100 | } 101 | 102 | const getQueryType = (args = {}) => { 103 | if (args._path) { 104 | return AEM_GRAPHQL_TYPES.BY_PATH 105 | } 106 | 107 | if (args.useLimitOffset) { 108 | return AEM_GRAPHQL_TYPES.LIST 109 | } 110 | 111 | return AEM_GRAPHQL_TYPES.PAGINATED 112 | } 113 | 114 | /** 115 | * Builds a GraphQL query string for the given parameters. 116 | * 117 | * @param {string} model - contentFragment Model Name 118 | * @param {string} fields - The query string for item fields 119 | * @param {ModelConfig} [config={}] - Pagination config 120 | * @param {ModelArgs} [args={}] - Query arguments 121 | * @returns {QueryBuilderResult} - object with The GraphQL query string and type 122 | */ 123 | const graphQLQueryBuilder = (model, fields, config = {}, args = {}) => { 124 | if (args._path) { 125 | return __modelByPath(model, fields, args) 126 | } 127 | 128 | if (config.useLimitOffset) { 129 | args.limit = args.limit || config.pageSize || 10 130 | if (config.after) { 131 | args.offset = args.offset || config.after 132 | } 133 | return __modelList(model, fields, args) 134 | } 135 | 136 | if (config.pageSize) { 137 | args.first = args.first || config.pageSize 138 | } 139 | 140 | if (config.after) { 141 | args.after = args.after || config.after 142 | } 143 | 144 | return __modelPaginated(model, fields, args) 145 | } 146 | 147 | module.exports = { 148 | graphQLQueryBuilder, 149 | getQueryType 150 | } 151 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 12 | 13 | [![Version](https://img.shields.io/npm/v/@adobe/aem-headless-client-js.svg)](https://npmjs.org/package/@adobe/aem-headless-client-js) 14 | [![Downloads/week](https://img.shields.io/npm/dw/@adobe/aem-headless-client-js.svg)](https://npmjs.org/package/@adobe/aem-headless-client-js) 15 | [![Build Status](https://github.com/adobe/aem-headless-client-js/workflows/Node.js%20CI/badge.svg?branch=main)](https://github.com/adobe/aem-headless-client-js/actions) 16 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 17 | 18 | # AEM Headless Client for JavaScript 19 | 20 | See [aem-headless-client-java](https://github.com/adobe/aem-headless-client-java) for the Java variant of this client 21 | and [aem-headless-client-nodejs](https://github.com/adobe/aem-headless-client-nodejs) for the server-side Node.js variant. 22 | 23 | ## Installation 24 | 25 | ```bash 26 | $ npm install @adobe/aem-headless-client-js 27 | ``` 28 | 29 | ## Usage 30 | 31 | ### Create AEMHeadless client 32 | 33 | ```javascript 34 | const AEMHeadless = require('@adobe/aem-headless-client-js'); 35 | ``` 36 | Configure SDK with Host and Auth data (if needed) 37 | ```javascript 38 | const aemHeadlessClient = new AEMHeadless({ 39 | serviceURL: '', 40 | endpoint: '', 41 | auth: '' || ['', ''], 42 | headers: {'': '', ...} 43 | }) 44 | // Eg: 45 | const aemHeadlessClient = new AEMHeadless({ 46 | serviceURL: AEM_HOST_URI, 47 | endpoint: 'content/graphql/endpoint.gql', 48 | auth: [AEM_USER, AEM_PASS], 49 | headers: {'customerheadername': 'customerheadervalue'} 50 | }) 51 | ``` 52 | ### Use AEMHeadless client 53 | 54 | #### Promise syntax: 55 | ```javascript 56 | aemHeadlessClient.runQuery(queryString) 57 | .then(data => console.log(data)) 58 | .catch(e => console.error(e.toJSON())) 59 | 60 | aemHeadlessClient.listPersistedQueries() 61 | .then(data => console.log(data)) 62 | .catch(e => console.error(e.toJSON())) 63 | 64 | aemHeadlessClient.persistQuery(queryString, 'wknd/persist-query-name') 65 | .then(data => console.log(data)) 66 | .catch(e => console.error(e.toJSON())) 67 | 68 | aemHeadlessClient.runPersistedQuery('wknd/persist-query-name') 69 | .then(data => console.log(data)) 70 | .catch(e => console.error(e.toJSON())) 71 | 72 | aemHeadlessClient.runPersistedQuery('wknd/persist-query-name-with-variables', { name: 'John Doe'}) 73 | .then(data => console.log(data)) 74 | .catch(e => console.error(e.toJSON())) 75 | ``` 76 | #### Within async/await: 77 | ```javascript 78 | (async () => { 79 | let postData 80 | try { 81 | postData = await aemHeadlessClient.runQuery(queryString) 82 | } catch (e) { 83 | console.error(e.toJSON()) 84 | } 85 | 86 | let list 87 | try { 88 | list = await aemHeadlessClient.listPersistedQueries() 89 | } catch (e) { 90 | console.error(e.toJSON()) 91 | } 92 | 93 | try { 94 | await aemHeadlessClient.persistQuery(queryString, 'wknd/persist-query-name') 95 | } catch (e) { 96 | console.error(e.toJSON()) 97 | } 98 | 99 | let getData 100 | try { 101 | getData = await aemHeadlessClient.runPersistedQuery('wknd/persist-query-name') 102 | } catch (e) { 103 | console.error(e.toJSON()) 104 | } 105 | })() 106 | ``` 107 | 108 | #### Pagination: 109 | ```javascript 110 | (async () => { 111 | const model = 'article' 112 | const fields = `{ 113 | title 114 | _path 115 | authorFragment { 116 | firstName 117 | profilePicture { 118 | ...on ImageRef { 119 | _authorUrl 120 | } 121 | } 122 | } 123 | }` 124 | 125 | // Loop all pages (default Cursor based) 126 | const cursorQueryAll = await aemHeadlessClient.runPaginatedQuery(model, fields, { pageSize: 3 }) 127 | for await (let value of cursorQueryAll) { 128 | console.log('cursorQueryAll', value) 129 | } 130 | // Manually get next page (default pageSize = 10) 131 | const cursorQuery = await aemHeadlessClient.runPaginatedQuery(model, fields) 132 | while (true) { 133 | const { done, value } = await cursorQuery.next(); 134 | if (done) break 135 | console.log('cursorQuery', value) 136 | } 137 | })() 138 | ``` 139 | 140 | ## Authorization 141 | 142 | If `auth` param is a string, it's treated as a Bearer token 143 | 144 | If `auth` param is an array, expected data is ['user', 'pass'] pair, and Basic Authorization will be used 145 | 146 | If `auth` is not defined, Authorization header will not be set 147 | 148 | ## API Reference 149 | 150 | See generated [API Reference](./api-reference.md) 151 | 152 | ## Contributing 153 | 154 | Contributions are welcome! Read the [Contributing Guide](./.github/CONTRIBUTING.md) for more information. 155 | 156 | ## Licensing 157 | 158 | This project is licensed under the Apache V2 License. See [LICENSE](LICENSE) for more information. 159 | -------------------------------------------------------------------------------- /test/shared/index.test.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 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 | Unless required by applicable law or agreed to in writing, software distributed under 7 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 8 | OF ANY KIND, either express or implied. See the License for the specific language 9 | governing permissions and limitations under the License. 10 | */ 11 | 12 | const { AEMHeadless, ErrorCodes } = require('../../src') 13 | // ///////////////////////////////////////////// 14 | const queryString = ` 15 | { 16 | adventureList { 17 | items { 18 | _path 19 | } 20 | } 21 | } 22 | ` 23 | const persistedName = 'wknd/persist-query-name' 24 | let sdk = {} 25 | 26 | beforeEach(() => { 27 | sdk = new AEMHeadless({ 28 | endpoint: 'endpoint/path.gql', 29 | serviceURL: 'http://localhost', 30 | auth: ['user', 'pass'] 31 | }) 32 | 33 | fetch.resetMocks() 34 | fetch.mockResolvedValue({ 35 | ok: true, 36 | status: 200, 37 | json: async () => ({ 38 | data: 'test' 39 | }) 40 | }) 41 | }) 42 | 43 | test('API: persistQuery API Success', () => { 44 | // check success response 45 | const promise = sdk.persistQuery(queryString, `${persistedName}-${Date.now()}`) 46 | return expect(promise).resolves.toBeTruthy() 47 | }) 48 | 49 | test('API: invalid serviceURL', () => { 50 | const serviceURL = 'invalid url path' 51 | const config = { 52 | serviceURL 53 | } 54 | sdk = new AEMHeadless(config) 55 | const promise = sdk.runQuery(queryString) 56 | return expect(promise).rejects.toThrow(`Invalid URL/path: ${serviceURL}`) 57 | }) 58 | 59 | test('API: persistQuery API Error', () => { 60 | fetch.mockRejectedValue({ 61 | ok: false 62 | }) 63 | // check error response 64 | const promise = sdk.persistQuery(queryString, persistedName) 65 | return expect(promise).rejects.toThrow() 66 | }) 67 | 68 | test('API: listPersistedQueries API Success', () => { 69 | const promise = sdk.listPersistedQueries() 70 | return expect(promise).resolves.toBeTruthy() 71 | }) 72 | 73 | test('API: runQuery API Success', () => { 74 | // check success response 75 | const promise = sdk.runQuery(queryString) 76 | return expect(promise).resolves.toBeTruthy() 77 | }) 78 | 79 | test('API: runQuery with variables API Success', () => { 80 | // check success response 81 | const promise = sdk.runQuery({ query: queryString, variables: { name: 'Ado' } }) 82 | return expect(promise).resolves.toBeTruthy() 83 | }) 84 | 85 | test('API: runQuery API Error', () => { 86 | fetch.mockRejectedValue({ 87 | ok: false 88 | }) 89 | // check error response 90 | const promise = sdk.runQuery() 91 | return expect(promise).rejects.toThrow() 92 | }) 93 | 94 | test('API: runPersistedQuery API Success', () => { 95 | // check success response 96 | const promise = sdk.runPersistedQuery(persistedName) 97 | return expect(promise).resolves.toBeTruthy() 98 | }) 99 | 100 | test('API: runPersistedQuery with variables API Success', () => { 101 | // check success response 102 | const promise = sdk.runPersistedQuery(persistedName, { name: 'test' }, { method: 'POST' }) 103 | return expect(promise).resolves.toBeTruthy() 104 | }) 105 | 106 | test('API: runPersistedQuery GET with variables API Success', () => { 107 | // check success response 108 | const promise = sdk.runPersistedQuery(persistedName, { name: 'test' }) 109 | expect(fetch).toHaveBeenCalledWith(`http://localhost/graphql/execute.json/${persistedName}%3Bname%3Dtest;`, expect.anything(), expect.anything()) 110 | return expect(promise).resolves.toBeTruthy() 111 | }) 112 | 113 | test('API: runPersistedQuery GET with two variables API Success', () => { 114 | // check success response 115 | const promise = sdk.runPersistedQuery(persistedName, { name: 'test', locale: 'en' }) 116 | expect(fetch).toHaveBeenCalledWith(`http://localhost/graphql/execute.json/${persistedName}%3Bname%3Dtest%3Blocale%3Den;`, expect.anything(), expect.anything()) 117 | return expect(promise).resolves.toBeTruthy() 118 | }) 119 | 120 | test('API: runPersistedQuery GET with no variables API Success', () => { 121 | // check success response 122 | const promise = sdk.runPersistedQuery(persistedName) 123 | expect(fetch).toHaveBeenCalledWith(`http://localhost/graphql/execute.json/${persistedName}`, expect.anything(), expect.anything()) 124 | return expect(promise).resolves.toBeTruthy() 125 | }) 126 | 127 | test('API: runPersistedQuery GET with no variables API Success and empty variables', () => { 128 | const promise = sdk.runPersistedQuery(persistedName, {}) 129 | expect(fetch).toHaveBeenCalledWith(`http://localhost/graphql/execute.json/${persistedName}`, expect.anything(), expect.anything()) 130 | return expect(promise).resolves.toBeTruthy() 131 | }) 132 | 133 | test('API: runPersistedQuery API Error', () => { 134 | fetch.mockRejectedValue({ 135 | ok: false 136 | }) 137 | // check error response 138 | const promise = sdk.runPersistedQuery('/test') 139 | return expect(promise).rejects.toThrow() 140 | }) 141 | // #181 2.2 Response error: JSON parsed - valid error defined in API response 142 | test('API: custom error message', () => { 143 | fetch.mockResolvedValue({ 144 | ok: false, 145 | json: async () => ({ 146 | error: { 147 | message: 'API custom error' 148 | } 149 | }) 150 | }) 151 | // check error response 152 | const promise = sdk.runPersistedQuery('/test') 153 | return expect(promise).rejects.toThrow(ErrorCodes.API_ERROR) 154 | }) 155 | // #175 2.3 Response error: Couldn't parse JSON - no error defined in API response 156 | test('API: Failed response JSON parsing error', () => { 157 | const JsonError = Error('JSON parse error') 158 | fetch.mockResolvedValue({ 159 | ok: false, 160 | json: async () => { 161 | throw JsonError 162 | } 163 | }) 164 | 165 | const promise = sdk.runPersistedQuery('/test') 166 | return expect(promise).rejects.toThrow(ErrorCodes.RESPONSE_ERROR) 167 | }) 168 | // #191 3.2. Response ok: Data error - Couldn't parse the JSON from OK response 169 | test('API: Successful response JSON parsing error', () => { 170 | const JsonError = Error('JSON parse error') 171 | fetch.mockResolvedValue({ 172 | ok: true, 173 | json: async () => { 174 | throw JsonError 175 | } 176 | }) 177 | 178 | const promise = sdk.runPersistedQuery('/test') 179 | return expect(promise).rejects.toThrow(ErrorCodes.RESPONSE_ERROR) 180 | }) 181 | 182 | test('ERROR: Error helper', () => { 183 | fetch.mockResolvedValue({ 184 | ok: false 185 | }) 186 | 187 | const promise = sdk.runPersistedQuery('/test') 188 | return promise.catch(e => { 189 | // eslint-disable-next-line 190 | return expect(e.toJSON()).toHaveProperty('message', e.message) 191 | }) 192 | }) 193 | 194 | test('API: auth as a token', () => { 195 | const config = { 196 | serviceURL: 'http://localhost', 197 | auth: 'token' 198 | } 199 | sdk = new AEMHeadless(config) 200 | const promise = sdk.runQuery(queryString) 201 | return expect(promise).resolves.toBeTruthy() 202 | }) 203 | 204 | test('API: additional request options', () => { 205 | const config = {} 206 | sdk = new AEMHeadless(config) 207 | const promise = sdk.runQuery(queryString, { method: 'GET' }) 208 | return expect(promise).resolves.toStrictEqual({ data: 'test' }) 209 | }) 210 | 211 | test('API: runQuery with custom headers API Success', () => { 212 | const config = { headers: { 'global-header': 'global-value' } } 213 | sdk = new AEMHeadless(config) 214 | const promise = sdk.runQuery(queryString, { headers: { 'custom-header': 'custom-value' } }) 215 | return expect(promise).resolves.toBeTruthy() 216 | }) 217 | 218 | test('API: params validation', () => { 219 | fetch.mockResolvedValue({ 220 | ok: false, 221 | json: async () => ({ 222 | errors: [{ 223 | message: 'API custom error' 224 | }] 225 | }) 226 | }) 227 | // check error response 228 | const promise = sdk.runQuery('/test') 229 | return expect(promise).rejects.toThrow(ErrorCodes.API_ERROR) 230 | }) 231 | 232 | test('API: custom API error missing', () => { 233 | fetch.mockResolvedValue({ 234 | ok: false, 235 | json: async () => ({}) 236 | }) 237 | 238 | const promise = sdk.runPersistedQuery('/test') 239 | return promise.catch(e => { 240 | // eslint-disable-next-line 241 | return expect(e.toJSON()).toHaveProperty('message', e.message) 242 | }) 243 | }) 244 | 245 | test('API: multiple API custom errors', () => { 246 | sdk = new AEMHeadless({ 247 | endpoint: {}, 248 | serviceURL: {} 249 | }) 250 | // check error response 251 | const promise = sdk.runPersistedQuery('/test') 252 | return expect(promise).rejects.toThrow('Invalid URL/path:') 253 | }) 254 | 255 | describe('runPaginatedQuery', () => { 256 | const mockModel = 'mockModel' 257 | const mockFields = 'mockFields' 258 | const mockConfig = { pageSize: 10 } 259 | const mockArgs = {} 260 | const mockOptions = {} 261 | const mockRetryOptions = {} 262 | 263 | it('should throw an error if model is missing', async () => { 264 | const gen = sdk.runPaginatedQuery(null, mockFields, mockConfig, mockArgs, mockOptions, mockRetryOptions) 265 | await expect(gen.next()).rejects.toThrow(ErrorCodes.INVALID_PARAM) 266 | }) 267 | 268 | it('should throw an error if fields are missing', async () => { 269 | const gen = sdk.runPaginatedQuery(mockModel, null, mockConfig, mockArgs, mockOptions, mockRetryOptions) 270 | await expect(gen.next()).rejects.toThrow(ErrorCodes.INVALID_PARAM) 271 | }) 272 | 273 | it('should yield the filtered data', async () => { 274 | const mockData = { id: '1', name: 'foo' } 275 | fetch.resetMocks() 276 | fetch.mockResolvedValue({ 277 | ok: true, 278 | status: 200, 279 | json: async () => ({ 280 | data: { 281 | mockModelPaginated: { 282 | edges: [ 283 | { node: mockData } 284 | ], 285 | pageInfo: {} 286 | } 287 | } 288 | }) 289 | }) 290 | 291 | const gen = sdk.runPaginatedQuery(mockModel, mockFields, mockConfig, mockArgs, mockOptions, mockRetryOptions) 292 | const result = await gen.next() 293 | 294 | expect(result).toEqual({ done: false, value: [mockData] }) 295 | }) 296 | }) 297 | -------------------------------------------------------------------------------- /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 2021 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. 202 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2020 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 | Unless required by applicable law or agreed to in writing, software distributed under 7 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 8 | OF ANY KIND, either express or implied. See the License for the specific language 9 | governing permissions and limitations under the License. 10 | */ 11 | 12 | const ErrorCodes = require('./utils/SDKErrors').codes 13 | const { AEM_GRAPHQL_ACTIONS, AEM_GRAPHQL_TYPES } = require('./utils/config') 14 | const { graphQLQueryBuilder, getQueryType } = require('./utils/GraphQLQueryBuilder') 15 | const { __getUrl, __getPath, __getDomain, __validateUrl, __getFetch, __getAuthHeader } = require('./utils/utils') 16 | const { REQUEST_ERROR, RESPONSE_ERROR, API_ERROR, INVALID_PARAM } = ErrorCodes 17 | 18 | /** 19 | * This class provides methods to call AEM GraphQL APIs. 20 | * Before calling any method initialize the instance 21 | * with GraphQL endpoint, GraphQL serviceURL and auth if needed 22 | */ 23 | class AEMHeadless { 24 | /** 25 | * Constructor. 26 | * 27 | * If param is a string, it's treated as AEM server URL, default GraphQL endpoint is used. 28 | * For granular params, use config object 29 | * 30 | * @param {string|object} config - Configuration object, or AEM server URL string 31 | * @param {string} [config.serviceURL] - AEM server URL 32 | * @param {string} [config.endpoint] - GraphQL endpoint 33 | * @param {(string|Array)} [config.auth] - Bearer token string or [user,pass] pair array 34 | * @param {object} [config.headers] - header { name: value, name: value, ... } 35 | * @param {object} [config.fetch] - custom Fetch instance 36 | */ 37 | constructor (config) { 38 | let endpoint = AEM_GRAPHQL_ACTIONS.endpoint 39 | let serviceURL = AEM_GRAPHQL_ACTIONS.serviceURL 40 | 41 | if (typeof config === 'string') { 42 | serviceURL = config 43 | } else { 44 | serviceURL = config.serviceURL || serviceURL 45 | endpoint = config.endpoint || endpoint 46 | this.auth = config.auth 47 | this.headers = config.headers 48 | } 49 | 50 | this.serviceURL = __getDomain(serviceURL) 51 | this.endpoint = __getPath(endpoint) 52 | this.fetch = __getFetch(config.fetch) 53 | } 54 | 55 | /** 56 | * Returns a Promise that resolves with a POST request JSON data. 57 | * 58 | * @param {string|object} body - the query string or an object with query (and optionally variables) as a property 59 | * @param {object} [options={}] - additional POST request options 60 | * @param {object} [retryOptions={}] - retry options for @adobe/aio-lib-core-networking 61 | * @returns {Promise} - the response body wrapped inside a Promise 62 | */ 63 | async runQuery (body, options = {}, retryOptions = {}) { 64 | const postBody = typeof body === 'object' ? body : { query: body } 65 | return this.__handleRequest(this.endpoint, JSON.stringify(postBody), options, retryOptions) 66 | } 67 | 68 | /** 69 | * Returns a Promise that resolves with a PUT request JSON data. 70 | * 71 | * @param {string} query - the query string 72 | * @param {string} path - AEM path to save query, format: configuration_name/endpoint_name 73 | * @param {object} [options={}] - additional PUT request options 74 | * @param {object} [retryOptions={}] - retry options for @adobe/aio-lib-core-networking 75 | * @returns {Promise} - the response body wrapped inside a Promise 76 | */ 77 | async persistQuery (query, path, options = {}, retryOptions = {}) { 78 | const url = `${AEM_GRAPHQL_ACTIONS.persist}/${path}` 79 | return this.__handleRequest(url, query, { method: 'PUT', ...options }, retryOptions) 80 | } 81 | 82 | /** 83 | * Returns a Promise that resolves with a GET request JSON data. 84 | * 85 | * @param {object} [options={}] - additional GET request options 86 | * @param {object} [retryOptions={}] - retry options for @adobe/aio-lib-core-networking 87 | * @returns {Promise} - the response body wrapped inside a Promise 88 | */ 89 | async listPersistedQueries (options = {}, retryOptions = {}) { 90 | const url = `${AEM_GRAPHQL_ACTIONS.list}` 91 | return this.__handleRequest(url, '', { method: 'GET', ...options }, retryOptions) 92 | } 93 | 94 | /** 95 | * Returns a Promise that resolves with a GET request JSON data. 96 | * 97 | * @param {string} path - AEM path for persisted query, format: configuration_name/endpoint_name 98 | * @param {object} [variables={}] - query variables 99 | * @param {object} [options={}] - additional GET request options 100 | * @param {object} [retryOptions={}] - retry options for @adobe/aio-lib-core-networking 101 | * @returns {Promise} - the response body wrapped inside a Promise 102 | */ 103 | 104 | async runPersistedQuery (path, variables = {}, options = {}, retryOptions = {}) { 105 | const method = (options.method || 'GET').toUpperCase() 106 | let body = '' 107 | let variablesString = encodeURIComponent(Object.keys(variables).map(key => { 108 | const val = (typeof variables[key] === 'string') ? variables[key] : JSON.stringify(variables[key]) 109 | return `;${key}=${val}` 110 | }).join('')) 111 | 112 | if (method === 'GET' && variablesString) { 113 | variablesString += ';' 114 | } 115 | 116 | if (method === 'POST') { 117 | body = JSON.stringify({ variables }) 118 | variablesString = '' 119 | } 120 | 121 | const url = `${AEM_GRAPHQL_ACTIONS.execute}/${path}${variablesString}` 122 | return this.__handleRequest(url, body, { method, ...options }, retryOptions) 123 | } 124 | 125 | /** 126 | * Returns a Generator Function. 127 | * 128 | * @generator 129 | * @param {string} model - contentFragment model name 130 | * @param {string} fields - The query string for item fields 131 | * @param {ModelConfig} [config={}] - Pagination config 132 | * @param {ModelArgs} [args={}] - Query arguments 133 | * @param {object} [options={}] - additional POST request options 134 | * @param {object} [retryOptions={}] - retry options for @adobe/aio-lib-core-networking 135 | * @yields {null | Promise} - the response items wrapped inside a Promise 136 | */ 137 | async * runPaginatedQuery (model, fields, config = {}, args = {}, options, retryOptions) { 138 | if (!model || !fields) { 139 | throw new INVALID_PARAM({ 140 | sdkDetails: { 141 | serviceURL: this.serviceURL 142 | }, 143 | messageValues: 'Required param missing: @param {string} fields - query string for item fields' 144 | }) 145 | } 146 | 147 | let isInitial = true 148 | let hasNext = true 149 | let after = args.after || '' 150 | const limit = args.limit 151 | const size = args.first || limit 152 | let pagingArgs = args 153 | while (hasNext) { 154 | const offset = pagingArgs.offset || 0 155 | if (!isInitial) { 156 | pagingArgs = this.__updatePagingArgs(args, { offset, limit, after }) 157 | } 158 | 159 | isInitial = false 160 | 161 | const { query, type } = this.buildQuery(model, fields, config, pagingArgs) 162 | const { data } = await this.runQuery(query, options, retryOptions) 163 | 164 | let filteredData = {} 165 | try { 166 | filteredData = this.__filterData(model, type, data, size) 167 | } catch (e) { 168 | throw new API_ERROR({ 169 | sdkDetails: { 170 | serviceURL: this.serviceURL 171 | }, 172 | messageValues: `Error while filtering response data. ${e.message}` 173 | }) 174 | } 175 | 176 | hasNext = filteredData.hasNext 177 | after = filteredData.endCursor 178 | 179 | yield filteredData.data 180 | } 181 | } 182 | 183 | /** 184 | * Builds a GraphQL query string for the given parameters. 185 | * 186 | * @param {string} model - contentFragment Model Name 187 | * @param {string} fields - The query string for item fields 188 | * @param {ModelConfig} [config={}] - Pagination config 189 | * @param {ModelArgs} [args={}] - Query arguments 190 | * @returns {QueryBuilderResult} - object with The GraphQL query string and type 191 | */ 192 | buildQuery (model, fields, config, args = {}) { 193 | return graphQLQueryBuilder(model, fields, config, args) 194 | } 195 | 196 | /** 197 | * Returns the updated paging arguments based on the current arguments and the response data. 198 | * 199 | * @private 200 | * @param {object} args - The current paging arguments. 201 | * @param {object} data - Current page arguments. 202 | * @param {string} data.after - The cursor to start after. 203 | * @param {number} data.offset - The offset to start from. 204 | * @param {number} [data.limit = 10] - The maximum number of items to return per page. 205 | * @returns {object} The updated paging arguments. 206 | */ 207 | __updatePagingArgs (args = {}, { after, offset, limit = 10 }) { 208 | const queryType = getQueryType(args) 209 | const pagingArgs = { ...args } 210 | if (queryType === AEM_GRAPHQL_TYPES.LIST) { 211 | pagingArgs.offset = offset + limit 212 | } 213 | 214 | if (queryType === AEM_GRAPHQL_TYPES.PAGINATED) { 215 | pagingArgs.after = after 216 | } 217 | 218 | return pagingArgs 219 | } 220 | 221 | /** 222 | * Returns items list and paging info. 223 | * 224 | * @private 225 | * @param {string} model - contentFragment model name 226 | * @param {string} type - model query type: byPath, List, Paginated 227 | * @param {object} data - raw response data 228 | * @param {number} size - page size 229 | * @returns {object} - object with filtered data and paging info 230 | */ 231 | __filterData (model, type, data, size = 0) { 232 | let response 233 | let filteredData 234 | let hasNext 235 | let endCursor 236 | let len 237 | switch (type) { 238 | case AEM_GRAPHQL_TYPES.BY_PATH: 239 | filteredData = data[`${model}${type}`].item 240 | hasNext = false 241 | break 242 | case AEM_GRAPHQL_TYPES.PAGINATED: 243 | response = data[`${model}${type}`] 244 | filteredData = response.edges.map(item => item.node) 245 | len = (filteredData && filteredData.length) || 0 246 | hasNext = response.pageInfo.hasNextPage && len > 0 && len >= size 247 | endCursor = response.pageInfo.endCursor 248 | break 249 | default: 250 | filteredData = data[`${model}${type}`].items 251 | len = (filteredData && filteredData.length) || 0 252 | hasNext = len > 0 && len >= size 253 | } 254 | 255 | return { 256 | data: filteredData, 257 | hasNext, 258 | endCursor 259 | } 260 | } 261 | 262 | /** 263 | * Returns an object for Request options 264 | * 265 | * @private 266 | * @param {string} [body] - Request body (the query string) 267 | * @param {object} [options] Additional Request options 268 | * @returns {object} the Request options object 269 | */ 270 | __getRequestOptions (body, options) { 271 | const { method = 'POST' } = options 272 | 273 | const requestOptions = { 274 | headers: { 275 | 'Content-Type': 'application/json' 276 | } 277 | } 278 | 279 | if (this.headers) { 280 | requestOptions.headers = { 281 | ...this.headers, 282 | ...requestOptions.headers 283 | } 284 | } 285 | 286 | if (this.auth) { 287 | requestOptions.headers = { 288 | ...requestOptions.headers, 289 | Authorization: __getAuthHeader(this.auth) 290 | } 291 | requestOptions.credentials = 'include' 292 | } 293 | 294 | return { 295 | method, 296 | ...body ? { body } : {}, 297 | ...requestOptions, 298 | ...options 299 | } 300 | } 301 | 302 | /** 303 | * Returns a Promise that resolves with a PUT request JSON data. 304 | * 305 | * @private 306 | * @param {string} endpoint - Request endpoint 307 | * @param {string} [body=''] - Request body (the query string) 308 | * @param {object} [options={}] - Request options 309 | * @param {object} [retryOptions={}] - retry options for @adobe/aio-lib-core-networking 310 | * @returns {Promise} the response body wrapped inside a Promise 311 | */ 312 | async __handleRequest (endpoint, body, options, retryOptions) { 313 | const requestOptions = this.__getRequestOptions(body, options) 314 | const url = __getUrl(this.serviceURL, endpoint) 315 | __validateUrl(url) 316 | 317 | let response 318 | // 1. Handle Request 319 | try { 320 | response = await this.fetch(url, requestOptions, retryOptions) 321 | } catch (error) { 322 | // 1.1 Request error: general 323 | throw new REQUEST_ERROR({ 324 | sdkDetails: { 325 | serviceURL: this.serviceURL, 326 | endpoint 327 | }, 328 | messageValues: error.message 329 | }) 330 | } 331 | 332 | let apiError 333 | const sdkDetails = { 334 | serviceURL: this.serviceURL, 335 | endpoint, 336 | status: response.status 337 | } 338 | // 2. Handle Response error 339 | if (!response.ok) { 340 | try { 341 | // 2.1 Check if custom error is returned 342 | apiError = await response.json() 343 | } catch (error) { 344 | // 2.3 Response error: Couldn't parse JSON - no error defined in API response 345 | throw new RESPONSE_ERROR({ 346 | sdkDetails, 347 | messageValues: error.message 348 | }) 349 | } 350 | } 351 | 352 | if (apiError) { 353 | // 2.2 Response error: JSON parsed - valid error defined in API response 354 | throw new API_ERROR({ 355 | sdkDetails, 356 | messageValues: apiError 357 | }) 358 | } 359 | // 3. Handle ok response 360 | let data 361 | try { 362 | data = await response.json() 363 | } catch (error) { 364 | // 3.2. Response ok: Data error - Couldn't parse the JSON from OK response 365 | throw new RESPONSE_ERROR({ 366 | sdkDetails, 367 | messageValues: error.message 368 | }) 369 | } 370 | // 3.2. Response ok: containing errors info 371 | if (data && data.errors) { 372 | throw new RESPONSE_ERROR({ 373 | sdkDetails, 374 | messageValues: data.errors.map((error) => error.message).join('. ') 375 | }) 376 | } 377 | 378 | return data 379 | } 380 | } 381 | 382 | module.exports = AEMHeadless 383 | module.exports.AEMHeadless = AEMHeadless 384 | module.exports.ErrorCodes = ErrorCodes 385 | -------------------------------------------------------------------------------- /api-reference.md: -------------------------------------------------------------------------------- 1 | 12 | # AEM HEADLESS SDK API Reference 13 | 14 | ## Classes 15 | 16 |
17 |
AEMHeadless
18 |

This class provides methods to call AEM GraphQL APIs. 19 | Before calling any method initialize the instance 20 | with GraphQL endpoint, GraphQL serviceURL and auth if needed

21 |
22 |
23 | 24 | ## Typedefs 25 | 26 |
27 |
Model : object
28 |

GraphQL Model type

29 |
30 |
ModelResult : object
31 |
32 |
ModelResults : object
33 |
34 |
ModelEdge : object
35 |
36 |
PageInfo : object
37 |
38 |
ModelConnection : object
39 |
40 |
ModelByPathArgs : object
41 |
42 |
ModelListArgs : object
43 |
44 |
ModelPaginatedArgs : object
45 |
46 |
ModelArgs : ModelByPathArgs | ModelListArgs | ModelPaginatedArgs
47 |
48 |
QueryBuilderResult : object
49 |
50 |
ModelConfig : object
51 |
52 |
53 | 54 | 55 | 56 | ## AEMHeadless 57 | This class provides methods to call AEM GraphQL APIs. 58 | Before calling any method initialize the instance 59 | with GraphQL endpoint, GraphQL serviceURL and auth if needed 60 | 61 | **Kind**: global class 62 | 63 | * [AEMHeadless](#AEMHeadless) 64 | * [new AEMHeadless(config)](#new_AEMHeadless_new) 65 | * [.runQuery(body, [options], [retryOptions])](#AEMHeadless+runQuery) ⇒ Promise.<any> 66 | * [.persistQuery(query, path, [options], [retryOptions])](#AEMHeadless+persistQuery) ⇒ Promise.<any> 67 | * [.listPersistedQueries([options], [retryOptions])](#AEMHeadless+listPersistedQueries) ⇒ Promise.<any> 68 | * [.runPersistedQuery(path, [variables], [options], [retryOptions])](#AEMHeadless+runPersistedQuery) ⇒ Promise.<any> 69 | * [.runPaginatedQuery(model, fields, [config], [args], [options], [retryOptions])](#AEMHeadless+runPaginatedQuery) 70 | * [.buildQuery(model, fields, [config], [args])](#AEMHeadless+buildQuery) ⇒ [QueryBuilderResult](#QueryBuilderResult) 71 | 72 | 73 | 74 | ### new AEMHeadless(config) 75 | Constructor. 76 | 77 | If param is a string, it's treated as AEM server URL, default GraphQL endpoint is used. 78 | For granular params, use config object 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 90 | 91 | 93 | 94 | 96 | 97 | 99 | 100 | 102 | 103 | 105 | 106 |
ParamTypeDescription
configstring | object

Configuration object, or AEM server URL string

89 |
[config.serviceURL]string

AEM server URL

92 |
[config.endpoint]string

GraphQL endpoint

95 |
[config.auth]string | Array

Bearer token string or [user,pass] pair array

98 |
[config.headers]object

header { name: value, name: value, ... }

101 |
[config.fetch]object

custom Fetch instance

104 |
107 | 108 | 109 | 110 | ### aemHeadless.runQuery(body, [options], [retryOptions]) ⇒ Promise.<any> 111 | Returns a Promise that resolves with a POST request JSON data. 112 | 113 | **Kind**: instance method of [AEMHeadless](#AEMHeadless) 114 | **Returns**: Promise.<any> - - the response body wrapped inside a Promise 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 125 | 126 | 128 | 129 | 131 | 132 |
ParamTypeDefaultDescription
bodystring | object

the query string or an object with query (and optionally variables) as a property

124 |
[options]object{}

additional POST request options

127 |
[retryOptions]object{}

retry options for @adobe/aio-lib-core-networking

130 |
133 | 134 | 135 | 136 | ### aemHeadless.persistQuery(query, path, [options], [retryOptions]) ⇒ Promise.<any> 137 | Returns a Promise that resolves with a PUT request JSON data. 138 | 139 | **Kind**: instance method of [AEMHeadless](#AEMHeadless) 140 | **Returns**: Promise.<any> - - the response body wrapped inside a Promise 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 151 | 152 | 154 | 155 | 157 | 158 | 160 | 161 |
ParamTypeDefaultDescription
querystring

the query string

150 |
pathstring

AEM path to save query, format: configuration_name/endpoint_name

153 |
[options]object{}

additional PUT request options

156 |
[retryOptions]object{}

retry options for @adobe/aio-lib-core-networking

159 |
162 | 163 | 164 | 165 | ### aemHeadless.listPersistedQueries([options], [retryOptions]) ⇒ Promise.<any> 166 | Returns a Promise that resolves with a GET request JSON data. 167 | 168 | **Kind**: instance method of [AEMHeadless](#AEMHeadless) 169 | **Returns**: Promise.<any> - - the response body wrapped inside a Promise 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 180 | 181 | 183 | 184 |
ParamTypeDefaultDescription
[options]object{}

additional GET request options

179 |
[retryOptions]object{}

retry options for @adobe/aio-lib-core-networking

182 |
185 | 186 | 187 | 188 | ### aemHeadless.runPersistedQuery(path, [variables], [options], [retryOptions]) ⇒ Promise.<any> 189 | Returns a Promise that resolves with a GET request JSON data. 190 | 191 | **Kind**: instance method of [AEMHeadless](#AEMHeadless) 192 | **Returns**: Promise.<any> - - the response body wrapped inside a Promise 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 203 | 204 | 206 | 207 | 209 | 210 | 212 | 213 |
ParamTypeDefaultDescription
pathstring

AEM path for persisted query, format: configuration_name/endpoint_name

202 |
[variables]object{}

query variables

205 |
[options]object{}

additional GET request options

208 |
[retryOptions]object{}

retry options for @adobe/aio-lib-core-networking

211 |
214 | 215 | 216 | 217 | ### aemHeadless.runPaginatedQuery(model, fields, [config], [args], [options], [retryOptions]) 218 | Returns a Generator Function. 219 | 220 | **Kind**: instance method of [AEMHeadless](#AEMHeadless) 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 231 | 232 | 234 | 235 | 237 | 238 | 240 | 241 | 243 | 244 | 246 | 247 |
ParamTypeDefaultDescription
modelstring

contentFragment model name

230 |
fieldsstring

The query string for item fields

233 |
[config]ModelConfig{}

Pagination config

236 |
[args]ModelArgs{}

Query arguments

239 |
[options]object{}

additional POST request options

242 |
[retryOptions]object{}

retry options for @adobe/aio-lib-core-networking

245 |
248 | 249 | 250 | 251 | ### aemHeadless.buildQuery(model, fields, [config], [args]) ⇒ [QueryBuilderResult](#QueryBuilderResult) 252 | Builds a GraphQL query string for the given parameters. 253 | 254 | **Kind**: instance method of [AEMHeadless](#AEMHeadless) 255 | **Returns**: [QueryBuilderResult](#QueryBuilderResult) - - object with The GraphQL query string and type 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 266 | 267 | 269 | 270 | 272 | 273 | 275 | 276 |
ParamTypeDefaultDescription
modelstring

contentFragment Model Name

265 |
fieldsstring

The query string for item fields

268 |
[config]ModelConfig{}

Pagination config

271 |
[args]ModelArgs{}

Query arguments

274 |
277 | 278 | 279 | 280 | ## Model : object 281 | GraphQL Model type 282 | 283 | **Kind**: global typedef 284 | **Properties** 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 296 | 297 |
NameTypeDescription
*any

model properties

295 |
298 | 299 | 300 | 301 | ## ModelResult : object 302 | **Kind**: global typedef 303 | **Properties** 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 315 | 316 |
NameTypeDescription
itemModel

response item

314 |
317 | 318 | 319 | 320 | ## ModelResults : object 321 | **Kind**: global typedef 322 | **Properties** 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 334 | 335 |
NameTypeDescription
itemsArray.<Model>

response items

333 |
336 | 337 | 338 | 339 | ## ModelEdge : object 340 | **Kind**: global typedef 341 | **Properties** 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 353 | 354 | 356 | 357 |
NameTypeDescription
cursorstring

item cursor

352 |
nodeModel

item node

355 |
358 | 359 | 360 | 361 | ## PageInfo : object 362 | **Kind**: global typedef 363 | **Properties** 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 375 | 376 | 378 | 379 | 381 | 382 | 384 | 385 |
NameTypeDescription
endCursorstring

endCursor

374 |
hasNextPageboolean

hasNextPage

377 |
hasPreviousPageboolean

hasPreviousPage

380 |
startCursorstring

startCursor

383 |
386 | 387 | 388 | 389 | ## ModelConnection : object 390 | **Kind**: global typedef 391 | **Properties** 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 403 | 404 | 406 | 407 |
NameTypeDescription
edgesArray.<ModelEdge>

edges

402 |
pageInfoPageInfo

pageInfo

405 |
408 | 409 | 410 | 411 | ## ModelByPathArgs : object 412 | **Kind**: global typedef 413 | **Properties** 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 425 | 426 | 428 | 429 |
NameTypeDescription
_pathstring

contentFragment path

424 |
variationstring

contentFragment variation

427 |
430 | 431 | 432 | 433 | ## ModelListArgs : object 434 | **Kind**: global typedef 435 | **Properties** 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 447 | 448 | 450 | 451 | 453 | 454 | 456 | 457 | 459 | 460 | 462 | 463 |
NameTypeDescription
[_locale]string

contentFragment locale

446 |
[variation]string

contentFragment variation

449 |
[filter]object

list filter options

452 |
[sort]string

list sort options

455 |
[offset]number

list offset

458 |
[limit]number

list limit

461 |
464 | 465 | 466 | 467 | ## ModelPaginatedArgs : object 468 | **Kind**: global typedef 469 | **Properties** 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 481 | 482 | 484 | 485 | 487 | 488 | 490 | 491 | 493 | 494 | 496 | 497 |
NameTypeDescription
[_locale]string

contentFragment locale

480 |
[variation]string

contentFragment variation

483 |
[filter]object

list filter options

486 |
[sort]string

list sort options

489 |
[first]number

number of list items

492 |
[after]string

list starting cursor

495 |
498 | 499 | 500 | 501 | ## ModelArgs : [ModelByPathArgs](#ModelByPathArgs) \| [ModelListArgs](#ModelListArgs) \| [ModelPaginatedArgs](#ModelPaginatedArgs) 502 | **Kind**: global typedef 503 | **Properties** 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 515 | 516 |
NameTypeDescription
*any

placeholder property

514 |
517 | 518 | 519 | 520 | ## QueryBuilderResult : object 521 | **Kind**: global typedef 522 | **Properties** 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 534 | 535 | 537 | 538 |
NameTypeDescription
typestring

Query type

533 |
queryQueryString

Query string

536 |
539 | 540 | 541 | 542 | ## ModelConfig : object 543 | **Kind**: global typedef 544 | **Properties** 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 | 556 | 557 | 559 | 560 | 562 | 563 |
NameTypeDefaultDescription
[pageSize]number10

page size

555 |
[after]string | number

starting cursor or offset

558 |
[useLimitOffset]booleanfalse

use offset pagination

561 |
564 | 565 | --------------------------------------------------------------------------------