mirror of
https://gitlab.com/openstapps/openstapps.git
synced 2026-01-03 12:02:53 +00:00
refactor: move api to monorepo
This commit is contained in:
15
packages/api/.editorconfig
Normal file
15
packages/api/.editorconfig
Normal file
@@ -0,0 +1,15 @@
|
||||
# editorconfig.org
|
||||
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
2
packages/api/.eslintignore
Normal file
2
packages/api/.eslintignore
Normal file
@@ -0,0 +1,2 @@
|
||||
resources
|
||||
openapi
|
||||
3
packages/api/.eslintrc.json
Normal file
3
packages/api/.eslintrc.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "@openstapps"
|
||||
}
|
||||
91
packages/api/.gitignore
vendored
Normal file
91
packages/api/.gitignore
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# TypeScript v1 declaration files
|
||||
typings/
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variables file
|
||||
.env
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
|
||||
# next.js build output
|
||||
.next
|
||||
|
||||
# nuxt.js build output
|
||||
.nuxt
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
#DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
########## end of https://github.com/github/gitignore/blob/master/Node.gitignore
|
||||
|
||||
# ignore ide files
|
||||
.idea
|
||||
.vscode
|
||||
|
||||
# ignore lib
|
||||
lib
|
||||
|
||||
# ignore docs
|
||||
docs
|
||||
124
packages/api/.gitlab-ci.yml
Normal file
124
packages/api/.gitlab-ci.yml
Normal file
@@ -0,0 +1,124 @@
|
||||
image: registry.gitlab.com/openstapps/projectmanagement/node
|
||||
|
||||
default:
|
||||
tags:
|
||||
- performance
|
||||
|
||||
before_script:
|
||||
- npm ci
|
||||
|
||||
stages:
|
||||
- build
|
||||
- test
|
||||
- audit
|
||||
- publish
|
||||
- deploy
|
||||
|
||||
build:
|
||||
stage: build
|
||||
script:
|
||||
- npm run build
|
||||
artifacts:
|
||||
paths:
|
||||
- lib
|
||||
|
||||
package:
|
||||
dependencies:
|
||||
- build
|
||||
tags:
|
||||
- secrecy
|
||||
stage: publish
|
||||
script:
|
||||
- echo "//registry.npmjs.org/:_authToken=$NPM_AUTH_TOKEN" > ~/.npmrc
|
||||
- npm publish
|
||||
only:
|
||||
- /^v[0-9]+.[0-9]+.[0-9]+$/
|
||||
artifacts:
|
||||
paths:
|
||||
- lib
|
||||
|
||||
audit:
|
||||
stage: audit
|
||||
script:
|
||||
- npm audit
|
||||
allow_failure: true
|
||||
except:
|
||||
- schedules
|
||||
|
||||
scheduled-audit:
|
||||
stage: audit
|
||||
script:
|
||||
- npm audit --audit-level=high
|
||||
only:
|
||||
- schedules
|
||||
|
||||
unit:
|
||||
stage: test
|
||||
script:
|
||||
- npm test
|
||||
coverage: '/Statements[^:]*\:[^:]*\s+([\d\.]+)%/'
|
||||
artifacts:
|
||||
reports:
|
||||
coverage_report:
|
||||
coverage_format: cobertura
|
||||
path: coverage/cobertura-coverage.xml
|
||||
|
||||
pages:
|
||||
stage: deploy
|
||||
script:
|
||||
- npm run documentation
|
||||
- mv docs public
|
||||
artifacts:
|
||||
paths:
|
||||
- public
|
||||
only:
|
||||
- /^v[0-9]+\.[0-9]+\.[0-9]+$/
|
||||
|
||||
docker image:
|
||||
image: registry.gitlab.com/openstapps/projectmanagement/builder:latest
|
||||
dependencies:
|
||||
- build
|
||||
stage: publish
|
||||
variables:
|
||||
DOCKER_DRIVER: overlay2
|
||||
services:
|
||||
- docker:dind
|
||||
script:
|
||||
- export VERSION=$(node -p "require('./package.json').version")
|
||||
- export CORE_VERSION=$(openstapps-projectmanagement get-used-version @openstapps/core)
|
||||
- export IMAGETAG_BASE=$CI_REGISTRY_IMAGE/cli
|
||||
- export IMAGETAG_CORE_VERSION=$IMAGETAG_BASE:core-$CORE_VERSION
|
||||
- export IMAGETAG_VERSION=$IMAGETAG_BASE:$VERSION
|
||||
- export IMAGETAG_LATEST=$IMAGETAG_BASE:latest
|
||||
- docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY
|
||||
- docker build -t $IMAGETAG_LATEST -t $IMAGETAG_VERSION -t $IMAGETAG_CORE_VERSION .
|
||||
- docker push $IMAGETAG_BASE
|
||||
tags:
|
||||
- secrecy
|
||||
only:
|
||||
- /^v[0-9]+\.[0-9]+\.[0-9]+$/
|
||||
|
||||
branch image:
|
||||
image: registry.gitlab.com/openstapps/projectmanagement/builder:latest
|
||||
stage: publish
|
||||
dependencies:
|
||||
- build
|
||||
artifacts:
|
||||
untracked: true
|
||||
variables:
|
||||
DOCKER_DRIVER: overlay2
|
||||
services:
|
||||
- docker:dind
|
||||
script:
|
||||
- export IMAGETAG_BASE=$CI_REGISTRY_IMAGE/$REGISTRY_BRANCH/cli
|
||||
- export IMAGETAG_BRANCH=$IMAGETAG_BASE:$CI_COMMIT_REF_SLUG
|
||||
- docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY
|
||||
- docker build -t $IMAGETAG_BRANCH .
|
||||
- docker push $IMAGETAG_BASE
|
||||
except:
|
||||
- /(^v[0-9]+\.[0-9]+\.[0-9]+$|^master$|^develop$)/
|
||||
only:
|
||||
- branches
|
||||
when: manual
|
||||
tags:
|
||||
- secrecy
|
||||
38
packages/api/.gitlab/issue_templates/bug.md
Normal file
38
packages/api/.gitlab/issue_templates/bug.md
Normal file
@@ -0,0 +1,38 @@
|
||||
## Summary
|
||||
|
||||
(Summarize the bug encountered concisely)
|
||||
|
||||
|
||||
## Steps to reproduce
|
||||
|
||||
(How one can reproduce the issue - this is very important)
|
||||
|
||||
|
||||
## Example Project
|
||||
|
||||
(If possible, please create an example project here on GitLab.com that exhibits the problematic behaviour, and link to it here in the bug report)
|
||||
|
||||
(If you are using an older version of GitLab, this will also determine whether the bug has been fixed in a more recent version)
|
||||
|
||||
|
||||
## What is the current bug behavior?
|
||||
|
||||
(What actually happens)
|
||||
|
||||
|
||||
## What is the expected correct behavior?
|
||||
|
||||
(What you should see instead)
|
||||
|
||||
|
||||
## Relevant logs and/or screenshots
|
||||
|
||||
(Paste any relevant logs - please use code blocks (```) to format console output,
|
||||
logs, and code as it's very hard to read otherwise.)
|
||||
|
||||
|
||||
## Possible fixes
|
||||
|
||||
(If you can, link to the line of code that might be responsible for the problem)
|
||||
|
||||
/label ~meeting
|
||||
16
packages/api/.gitlab/issue_templates/feature.md
Normal file
16
packages/api/.gitlab/issue_templates/feature.md
Normal file
@@ -0,0 +1,16 @@
|
||||
## Description
|
||||
|
||||
(Describe the feature that you're requesting concisely)
|
||||
|
||||
|
||||
## Explanation
|
||||
|
||||
(Explain why the feature is necessary)
|
||||
|
||||
|
||||
## Dependencies, issues to be resolved beforehand
|
||||
|
||||
(List issues or dependencies that need to be resolved before this feature can be implemented)
|
||||
|
||||
|
||||
/label ~meeting
|
||||
11
packages/api/.npmignore
Normal file
11
packages/api/.npmignore
Normal file
@@ -0,0 +1,11 @@
|
||||
# Ignore all files/folders by default
|
||||
# See https://stackoverflow.com/a/29932318
|
||||
/*
|
||||
# Except these files/folders
|
||||
!lib
|
||||
lib/tsconfig.tsbuildinfo
|
||||
!LICENSE
|
||||
!package.json
|
||||
!package-lock.json
|
||||
!README.md
|
||||
!src
|
||||
286
packages/api/CHANGELOG.md
Normal file
286
packages/api/CHANGELOG.md
Normal file
@@ -0,0 +1,286 @@
|
||||
# [0.45.0](https://gitlab.com/openstapps/api/compare/v0.44.0...v0.45.0) (2022-12-06)
|
||||
|
||||
|
||||
|
||||
# [0.44.0](https://gitlab.com/openstapps/api/compare/v0.43.0...v0.44.0) (2022-10-18)
|
||||
|
||||
|
||||
|
||||
# [0.43.0](https://gitlab.com/openstapps/api/compare/v0.42.0...v0.43.0) (2022-08-23)
|
||||
|
||||
|
||||
|
||||
# [0.42.0](https://gitlab.com/openstapps/api/compare/v0.41.1...v0.42.0) (2022-07-04)
|
||||
|
||||
|
||||
|
||||
## [0.41.1](https://gitlab.com/openstapps/api/compare/v0.41.0...v0.41.1) (2022-05-27)
|
||||
|
||||
|
||||
|
||||
# [0.41.0](https://gitlab.com/openstapps/api/compare/v0.40.0...v0.41.0) (2022-05-17)
|
||||
|
||||
|
||||
|
||||
# [0.40.0](https://gitlab.com/openstapps/api/compare/v0.39.0...v0.40.0) (2022-04-04)
|
||||
|
||||
|
||||
|
||||
# [0.39.0](https://gitlab.com/openstapps/api/compare/v0.38.0...v0.39.0) (2022-03-17)
|
||||
|
||||
|
||||
|
||||
# [0.38.0](https://gitlab.com/openstapps/api/compare/v0.37.0...v0.38.0) (2022-01-25)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add client method for invoking plugin routes ([83120a6](https://gitlab.com/openstapps/api/commit/83120a67345d2fee672f6a44ab91708ecce65e58))
|
||||
|
||||
|
||||
|
||||
# [0.37.0](https://gitlab.com/openstapps/api/compare/v0.36.0...v0.37.0) (2021-12-17)
|
||||
|
||||
|
||||
|
||||
# [0.36.0](https://gitlab.com/openstapps/api/compare/v0.35.0...v0.36.0) (2021-12-15)
|
||||
|
||||
|
||||
|
||||
# [0.35.0](https://gitlab.com/openstapps/api/compare/v0.34.0...v0.35.0) (2021-10-20)
|
||||
|
||||
|
||||
|
||||
# [0.34.0](https://gitlab.com/openstapps/api/compare/v0.33.0...v0.34.0) (2021-10-04)
|
||||
|
||||
|
||||
|
||||
# [0.33.0](https://gitlab.com/openstapps/api/compare/v0.32.0...v0.33.0) (2021-09-16)
|
||||
|
||||
|
||||
|
||||
# [0.32.0](https://gitlab.com/openstapps/api/compare/v0.31.1...v0.32.0) (2021-09-01)
|
||||
|
||||
|
||||
|
||||
## [0.31.1](https://gitlab.com/openstapps/api/compare/v0.31.0...v0.31.1) (2021-08-27)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* plugin related tests ([51c157d](https://gitlab.com/openstapps/api/commit/51c157d577b9ae70e8c4683e653cd65aacb4f248))
|
||||
|
||||
|
||||
|
||||
# [0.31.0](https://gitlab.com/openstapps/api/compare/v0.30.0...v0.31.0) (2021-08-17)
|
||||
|
||||
|
||||
|
||||
# [0.30.0](https://gitlab.com/openstapps/api/compare/v0.29.0...v0.30.0) (2021-08-04)
|
||||
|
||||
|
||||
|
||||
# [0.29.0](https://gitlab.com/openstapps/api/compare/v0.28.0...v0.29.0) (2021-06-08)
|
||||
|
||||
|
||||
|
||||
# [0.28.0](https://gitlab.com/openstapps/api/compare/v0.27.0...v0.28.0) (2021-04-27)
|
||||
|
||||
|
||||
|
||||
# [0.27.0](https://gitlab.com/openstapps/api/compare/v0.26.0...v0.27.0) (2021-03-08)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* send valid JSON on bulk/done ([29cd22f](https://gitlab.com/openstapps/api/commit/29cd22f2d11cebbe2de63cc2e614734e286821f2)), closes [#38](https://gitlab.com/openstapps/api/issues/38)
|
||||
|
||||
|
||||
|
||||
# [0.26.0](https://gitlab.com/openstapps/api/compare/v0.25.0...v0.26.0) (2021-02-23)
|
||||
|
||||
|
||||
|
||||
# [0.25.0](https://gitlab.com/openstapps/api/compare/v0.23.0...v0.25.0) (2020-11-09)
|
||||
|
||||
|
||||
|
||||
# [0.23.0](https://gitlab.com/openstapps/api/compare/v0.22.0...v0.23.0) (2020-10-23)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* make express parse body ([b3e1075](https://gitlab.com/openstapps/api/commit/b3e107528b5d6ac5ec86786a9f9bf8fb1645e874))
|
||||
|
||||
|
||||
|
||||
# [0.22.0](https://gitlab.com/openstapps/api/compare/v0.21.0...v0.22.0) (2020-05-15)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add content-type header ([d30de89](https://gitlab.com/openstapps/api/commit/d30de896f0d1a21c039e1905c0766cc37df06b23))
|
||||
|
||||
|
||||
|
||||
# [0.21.0](https://gitlab.com/openstapps/api/compare/v0.19.0...v0.21.0) (2020-05-06)
|
||||
|
||||
|
||||
|
||||
# [0.19.0](https://gitlab.com/openstapps/api/compare/v0.18.0...v0.19.0) (2020-03-11)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* repair and unify subcommand help outputs ([4ae968f](https://gitlab.com/openstapps/api/commit/4ae968ff0f52c940cb11a97876f72d57feb61597))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add option to wait on resource to e2e script ([e18858f](https://gitlab.com/openstapps/api/commit/e18858fc58ccfb8b3bdec92260eba12cd1a25214))
|
||||
|
||||
|
||||
|
||||
# [0.18.0](https://gitlab.com/openstapps/api/compare/v0.17.0...v0.18.0) (2020-02-04)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* extend e2e procedure ([dc79dc8](https://gitlab.com/openstapps/api/commit/dc79dc8feb10a29cff0f6d1c320658ad13cf7e4e))
|
||||
|
||||
|
||||
|
||||
# [0.17.0](https://gitlab.com/openstapps/api/compare/v0.16.0...v0.17.0) (2019-11-15)
|
||||
|
||||
|
||||
|
||||
# [0.16.0](https://gitlab.com/openstapps/api/compare/v0.15.0...v0.16.0) (2019-09-03)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add plugin class ([c2848fc](https://gitlab.com/openstapps/api/commit/c2848fc7a528288ef4c3ab96728d4e16add6fe75)), closes [#12](https://gitlab.com/openstapps/api/issues/12)
|
||||
|
||||
|
||||
|
||||
# [0.15.0](https://gitlab.com/openstapps/api/compare/v0.14.0...v0.15.0) (2019-08-19)
|
||||
|
||||
|
||||
|
||||
# [0.14.0](https://gitlab.com/openstapps/api/compare/v0.13.0...v0.14.0) (2019-07-23)
|
||||
|
||||
|
||||
|
||||
# [0.13.0](https://gitlab.com/openstapps/api/compare/v0.12.0...v0.13.0) (2019-07-16)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* change removeReferences() to also remove origin ([ded221c](https://gitlab.com/openstapps/api/commit/ded221c175368d315fdbb79d561c86c3ee8bf158))
|
||||
|
||||
|
||||
|
||||
# [0.12.0](https://gitlab.com/openstapps/api/compare/v0.11.0...v0.12.0) (2019-07-15)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add function to remove undefined properties ([f95fd09](https://gitlab.com/openstapps/api/commit/f95fd09112e81eab42591a5aaff3568ab06e9441))
|
||||
|
||||
|
||||
|
||||
# [0.11.0](https://gitlab.com/openstapps/api/compare/v0.10.0...v0.11.0) (2019-07-12)
|
||||
|
||||
|
||||
|
||||
# [0.10.0](https://gitlab.com/openstapps/api/compare/v0.9.0...v0.10.0) (2019-07-03)
|
||||
|
||||
|
||||
|
||||
# [0.9.0](https://gitlab.com/openstapps/api/compare/v0.8.0...v0.9.0) (2019-06-20)
|
||||
|
||||
|
||||
|
||||
# [0.8.0](https://gitlab.com/openstapps/api/compare/v0.7.0...v0.8.0) (2019-05-14)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add e2e command. Indexes core test files. ([e1313b5](https://gitlab.com/openstapps/api/commit/e1313b55ff3bc17e96b09639f4949b2179991679))
|
||||
|
||||
|
||||
|
||||
# [0.7.0](https://gitlab.com/openstapps/api/compare/v0.6.0...v0.7.0) (2019-04-16)
|
||||
|
||||
|
||||
|
||||
# [0.6.0](https://gitlab.com/openstapps/api/compare/v0.5.0...v0.6.0) (2019-04-09)
|
||||
|
||||
|
||||
|
||||
# [0.5.0](https://gitlab.com/openstapps/api/compare/v0.4.1...v0.5.0) (2019-04-04)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add method to remove references from a thing ([9cf6fde](https://gitlab.com/openstapps/api/commit/9cf6fde050c665b63026b8c08502c7836e23c2d5)), closes [#6](https://gitlab.com/openstapps/api/issues/6)
|
||||
|
||||
|
||||
|
||||
## [0.4.1](https://gitlab.com/openstapps/api/compare/v0.4.0...v0.4.1) (2019-03-15)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* adjust compile npm script to exact configuration guideline ([7f8c9ed](https://gitlab.com/openstapps/api/commit/7f8c9eda2fdcef0831af23806b846baa0d236a1c))
|
||||
|
||||
|
||||
|
||||
# [0.4.0](https://gitlab.com/openstapps/api/compare/v0.3.0...v0.4.0) (2019-03-15)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* apply changes suggested by @openstapps/configuration ([782fdbe](https://gitlab.com/openstapps/api/commit/782fdbebba3599323a98244fcc28e7605ed95cc2))
|
||||
|
||||
|
||||
|
||||
# [0.3.0](https://gitlab.com/openstapps/api/compare/v0.2.0...v0.3.0) (2019-02-21)
|
||||
|
||||
|
||||
|
||||
# [0.2.0](https://gitlab.com/openstapps/api/compare/v0.1.1...v0.2.0) (2019-02-18)
|
||||
|
||||
|
||||
|
||||
## [0.1.1](https://gitlab.com/openstapps/api/compare/v0.1.0...v0.1.1) (2019-02-07)
|
||||
|
||||
|
||||
|
||||
# [0.1.0](https://gitlab.com/openstapps/api/compare/v0.0.3...v0.1.0) (2019-01-28)
|
||||
|
||||
|
||||
|
||||
## [0.0.3](https://gitlab.com/openstapps/api/compare/v0.0.2...v0.0.3) (2019-01-21)
|
||||
|
||||
|
||||
|
||||
## [0.0.2](https://gitlab.com/openstapps/api/compare/v0.0.1...v0.0.2) (2018-12-14)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add type and batchSize to required parameters ([8541b00](https://gitlab.com/openstapps/api/commit/8541b00dbbf4c683fddaf3d003cf13fabfbc979b)), closes [#1](https://gitlab.com/openstapps/api/issues/1)
|
||||
* remove trailing slash from url if needed ([eb7c334](https://gitlab.com/openstapps/api/commit/eb7c334bb8878cffd96cd9d52b5b99e2338e3a65))
|
||||
|
||||
|
||||
|
||||
## [0.0.1](https://gitlab.com/openstapps/api/compare/4839f941c617681c78ef9959f3df86013459c332...v0.0.1) (2018-11-29)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add api ([4839f94](https://gitlab.com/openstapps/api/commit/4839f941c617681c78ef9959f3df86013459c332))
|
||||
|
||||
|
||||
|
||||
8
packages/api/Dockerfile
Normal file
8
packages/api/Dockerfile
Normal file
@@ -0,0 +1,8 @@
|
||||
FROM registry.gitlab.com/openstapps/projectmanagement/node
|
||||
|
||||
ADD . /app
|
||||
WORKDIR /app
|
||||
|
||||
ENTRYPOINT ["node", "lib/cli.js"]
|
||||
|
||||
CMD ["--help"]
|
||||
200
packages/api/LICENSE
Normal file
200
packages/api/LICENSE
Normal file
@@ -0,0 +1,200 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
|
||||
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
|
||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
|
||||
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||
13. Use with the GNU Affero General Public License.
|
||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
|
||||
14. Revised Versions of this License.
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
16. Limitation of Liability.
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/ licenses/why-not-lgpl.html>.
|
||||
67
packages/api/README.md
Normal file
67
packages/api/README.md
Normal file
@@ -0,0 +1,67 @@
|
||||
# @openstapps/api
|
||||
|
||||
Node.js library to interact with the StApps backend service
|
||||
|
||||
## Use this as a standalone program
|
||||
|
||||
To get some data into a local `backend-node`-instance, you can run this
|
||||
as a standalone program to copy data of a remote `backend-node`-instance
|
||||
into your local one.
|
||||
|
||||
Example to copy all Events of the b-tu instance:
|
||||
|
||||
```shell
|
||||
npm install
|
||||
npm run build
|
||||
node ./lib/cli.js copy Event https://stappsbe01.innocampus.tu-berlin.de http://localhost:3000 100
|
||||
```
|
||||
|
||||
Example to index all items from @openstapps/core test files to a backend:
|
||||
|
||||
```shell
|
||||
npm install
|
||||
npm run build
|
||||
node ./lib/cli.js e2e http://localhost:3000
|
||||
```
|
||||
|
||||
### Program arguments
|
||||
|
||||
```shell
|
||||
node ./lib/cli.js copy <type> <from> <to> <batchSize>
|
||||
|
||||
node ./lib/cli.js e2e <to>
|
||||
```
|
||||
|
||||
#### Options
|
||||
|
||||
The source identifier for the bulk to use with the target instance (default is 'copy')
|
||||
|
||||
```shell
|
||||
-s, --bulkSource <bulkScource>
|
||||
```
|
||||
|
||||
The App version to use (unset by default)
|
||||
|
||||
```shell
|
||||
-a, --appVersion <version>
|
||||
```
|
||||
|
||||
The only available option for `e2e` command. File path to json test files each containing a SCThing.
|
||||
|
||||
```shell
|
||||
-s, --samples <path>
|
||||
```
|
||||
|
||||
### Example execution
|
||||
|
||||
with docker when backend is running on `localhost:3000`:
|
||||
|
||||
```shell
|
||||
docker run --net=host registry.gitlab.com/openstapps/api/cli copy Place https://stappsbe01.innocampus.tu-berlin.de http://localhost:3000 100
|
||||
```
|
||||
|
||||
Or using `e2e` command:
|
||||
|
||||
```shell
|
||||
docker run --net=host registry.gitlab.com/openstapps/api/cli e2e http://localhost:3000
|
||||
```
|
||||
6329
packages/api/package-lock.json
generated
Normal file
6329
packages/api/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
125
packages/api/package.json
Normal file
125
packages/api/package.json
Normal file
@@ -0,0 +1,125 @@
|
||||
{
|
||||
"name": "@openstapps/api",
|
||||
"version": "0.45.0",
|
||||
"scripts": {
|
||||
"build": "npm run lint && npm run compile",
|
||||
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0 && git add CHANGELOG.md && git commit -m 'docs: update changelog'",
|
||||
"check-configuration": "openstapps-configuration",
|
||||
"compile": "rimraf lib && tsc && prepend lib/cli.js '#!/usr/bin/env node\n'",
|
||||
"documentation": "typedoc --includeVersion --out docs --readme README.md --listInvalidSymbolLinks --entryPointStrategy expand src",
|
||||
"postversion": "npm run changelog",
|
||||
"prepublishOnly": "npm ci && npm run build",
|
||||
"preversion": "npm run prepublishOnly",
|
||||
"push": "git push && git push origin \"v$npm_package_version\"",
|
||||
"test": "nyc mocha --recursive 'test/*.spec.ts'",
|
||||
"lint": "eslint --ext .ts src/"
|
||||
},
|
||||
"description": "Node.js library to interact with the StApps backend service",
|
||||
"dependencies": {
|
||||
"@krlwlfrt/async-pool": "0.7.0",
|
||||
"@openstapps/core": "0.72.0",
|
||||
"@openstapps/core-tools": "0.32.0",
|
||||
"@openstapps/logger": "1.1.1",
|
||||
"@types/cli-progress": "3.11.0",
|
||||
"@types/express": "4.17.14",
|
||||
"@types/morgan": "1.9.3",
|
||||
"@types/node": "14.18.34",
|
||||
"@types/traverse": "0.6.32",
|
||||
"@types/uuid": "8.3.4",
|
||||
"@types/wait-on": "5.3.1",
|
||||
"body-parser": "1.20.1",
|
||||
"cli-progress": "3.11.2",
|
||||
"commander": "9.4.1",
|
||||
"express": "4.18.2",
|
||||
"got": "11.8.5",
|
||||
"json-schema": "0.4.0",
|
||||
"moment": "2.29.4",
|
||||
"morgan": "1.10.0",
|
||||
"rfdc": "1.3.0",
|
||||
"traverse": "0.6.7",
|
||||
"uuid": "8.3.2",
|
||||
"wait-on": "6.0.1"
|
||||
},
|
||||
"license": "GPL-3.0-only",
|
||||
"devDependencies": {
|
||||
"@openstapps/configuration": "0.33.0",
|
||||
"@openstapps/eslint-config": "1.1.0",
|
||||
"@testdeck/mocha": "0.3.3",
|
||||
"@types/chai": "4.3.4",
|
||||
"@types/chai-as-promised": "7.1.5",
|
||||
"@types/chai-spies": "1.0.3",
|
||||
"@types/fs-extra": "9.0.13",
|
||||
"@types/json-schema": "7.0.11",
|
||||
"@types/mocha": "9.1.1",
|
||||
"@typescript-eslint/eslint-plugin": "5.40.1",
|
||||
"@typescript-eslint/parser": "5.40.1",
|
||||
"chai": "4.3.7",
|
||||
"chai-as-promised": "7.1.1",
|
||||
"chai-spies": "1.0.0",
|
||||
"conventional-changelog-cli": "2.2.2",
|
||||
"eslint": "8.29.0",
|
||||
"eslint-config-prettier": "8.5.0",
|
||||
"eslint-plugin-jsdoc": "39.6.4",
|
||||
"eslint-plugin-prettier": "4.2.1",
|
||||
"eslint-plugin-unicorn": "43.0.2",
|
||||
"fs-extra": "10.1.0",
|
||||
"mocha": "10.1.0",
|
||||
"nock": "13.2.9",
|
||||
"nyc": "15.1.0",
|
||||
"prepend-file-cli": "1.0.6",
|
||||
"prettier": "2.8.0",
|
||||
"rimraf": "3.0.2",
|
||||
"ts-node": "10.9.1",
|
||||
"tslint": "6.1.3",
|
||||
"typedoc": "0.22.18",
|
||||
"typescript": "4.4.4"
|
||||
},
|
||||
"author": "Karl-Philipp Wulfert <krlwlfrt@gmail.com>",
|
||||
"contributors": [
|
||||
"André Michael Thomas Bierlein",
|
||||
"Anselm Stordeur <anselmstordeur@gmail.com>",
|
||||
"Jovan Krunić <jovan.krunic@gmail.com>",
|
||||
"Michel Jonathan Schmitz",
|
||||
"Rainer Killinger <mail-openstapps@killinger.co>",
|
||||
"Roman Klopsch",
|
||||
"Thea Schöbl <dev@theaninova.de>"
|
||||
],
|
||||
"peerDependencies": {
|
||||
"@openstapps/core": "~0.72.0"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git@gitlab.com:openstapps/api.git"
|
||||
},
|
||||
"bin": {
|
||||
"openstapps-api": "./lib/cli.js"
|
||||
},
|
||||
"main": "lib/client.js",
|
||||
"typings": "lib/index.d.ts",
|
||||
"nyc": {
|
||||
"all": true,
|
||||
"branches": 95,
|
||||
"check-coverage": true,
|
||||
"exclude": [
|
||||
"src/cli.ts"
|
||||
],
|
||||
"extension": [
|
||||
".ts"
|
||||
],
|
||||
"functions": 95,
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"lines": 95,
|
||||
"per-file": true,
|
||||
"reporter": [
|
||||
"cobertura",
|
||||
"html",
|
||||
"text-summary"
|
||||
],
|
||||
"require": [
|
||||
"ts-node/register"
|
||||
],
|
||||
"statements": 95
|
||||
}
|
||||
}
|
||||
91
packages/api/src/bulk.ts
Normal file
91
packages/api/src/bulk.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Copyright (C) 2018-2022 Open StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {
|
||||
SCBulkAddResponse,
|
||||
SCBulkAddRoute,
|
||||
SCBulkDoneResponse,
|
||||
SCBulkDoneRoute,
|
||||
SCBulkResponse,
|
||||
SCThings,
|
||||
SCThingType,
|
||||
} from '@openstapps/core';
|
||||
import {Client} from './client';
|
||||
import {BulkWithMultipleTypesError} from './errors';
|
||||
|
||||
/**
|
||||
* A bulk
|
||||
*
|
||||
* **!!! Bulk should only be instantiated by Client !!!**
|
||||
*/
|
||||
export class Bulk<T extends SCThings> {
|
||||
/**
|
||||
* Instance of multi search request route
|
||||
*/
|
||||
private readonly bulkAddRoute = new SCBulkAddRoute();
|
||||
|
||||
/**
|
||||
* Instance of multi search request route
|
||||
*/
|
||||
private readonly bulkDoneRoute = new SCBulkDoneRoute();
|
||||
|
||||
/**
|
||||
* **!!! Bulk should only be instantiated by Client !!!**
|
||||
*
|
||||
* @see Client.bulk
|
||||
*/
|
||||
constructor(
|
||||
private readonly type: SCThingType,
|
||||
private readonly client: Client,
|
||||
private readonly bulkResponse: SCBulkResponse,
|
||||
) {
|
||||
// noop
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a thing to the bulk
|
||||
*
|
||||
* @param thing Thing to add to the bulk
|
||||
*/
|
||||
async add(thing: T): Promise<SCBulkAddResponse> {
|
||||
// check that thing has same type as bulk
|
||||
if (this.type !== thing.type) {
|
||||
throw new BulkWithMultipleTypesError(thing);
|
||||
}
|
||||
|
||||
return this.client.invokeRoute<SCBulkAddResponse>(
|
||||
this.bulkAddRoute,
|
||||
{
|
||||
UID: encodeURIComponent(this.bulkResponse.uid),
|
||||
},
|
||||
thing,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare this bulk transfer as done
|
||||
*
|
||||
* This will activate the index in the backend and possibly delete old data. There are many potential processing steps
|
||||
* required in the backend so it might take a few seconds before the callback is called.
|
||||
*/
|
||||
async done(): Promise<SCBulkDoneResponse> {
|
||||
return this.client.invokeRoute<SCBulkDoneResponse>(
|
||||
this.bulkDoneRoute,
|
||||
{
|
||||
UID: this.bulkResponse.uid,
|
||||
},
|
||||
{},
|
||||
);
|
||||
}
|
||||
}
|
||||
138
packages/api/src/cli.ts
Normal file
138
packages/api/src/cli.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
* Copyright (C) 2018-2022 Open StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {SCThingType} from '@openstapps/core';
|
||||
import {Logger} from '@openstapps/logger';
|
||||
import {Command} from 'commander';
|
||||
import {readFileSync} from 'fs';
|
||||
import path from 'path';
|
||||
import {URL} from 'url';
|
||||
import waitOn from 'wait-on';
|
||||
import {copy} from './copy';
|
||||
// eslint-disable-next-line unicorn/prevent-abbreviations
|
||||
import {e2eRun} from './e2e';
|
||||
import {HttpClient} from './http-client';
|
||||
|
||||
process.on('unhandledRejection', async error => {
|
||||
await Logger.error('unhandledRejection', error);
|
||||
});
|
||||
|
||||
// eslint-disable-next-line unicorn/prefer-module
|
||||
const packageJson = JSON.parse(readFileSync(path.join(__dirname, '..', 'package.json')).toString());
|
||||
|
||||
const client = new HttpClient();
|
||||
const commander = new Command();
|
||||
const helpAndExit = (help: string) => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(help);
|
||||
process.exit(-1);
|
||||
};
|
||||
|
||||
commander
|
||||
.command('e2e <to>')
|
||||
.version(packageJson.version)
|
||||
.description(
|
||||
'Run in end to end test mode. Indexing and afterwards retrieving all test files from @openstapp/core to the backend',
|
||||
)
|
||||
.option(
|
||||
'-s --samples [path]',
|
||||
'Path to @openstapp/core test files',
|
||||
'./node_modules/@openstapps/core/test/resources/indexable',
|
||||
)
|
||||
.option('-w --waiton [resource]', 'wait-on resource parameter see "www.npmjs.com/wait-on"')
|
||||
// eslint-disable-next-line unicorn/prevent-abbreviations
|
||||
.action(async (to, e2eCommand) => {
|
||||
let toURL = '';
|
||||
// validate url
|
||||
try {
|
||||
toURL = new URL(to).toString();
|
||||
} catch (error) {
|
||||
await Logger.error('expected parameter <to> to be valid url', error);
|
||||
helpAndExit(e2eCommand.helpInformation());
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof e2eCommand.waiton === 'string') {
|
||||
Logger.info(`Waiting for availibilty of resource: ${e2eCommand.waiton}`);
|
||||
await waitOn({
|
||||
resources: [e2eCommand.waiton],
|
||||
timeout: 300_000,
|
||||
});
|
||||
Logger.info(`Resource became available`);
|
||||
}
|
||||
await e2eRun(client, {to: toURL, samplesLocation: e2eCommand.samples});
|
||||
Logger.ok('Done');
|
||||
} catch (error) {
|
||||
await Logger.error(error);
|
||||
}
|
||||
});
|
||||
|
||||
commander
|
||||
.command('copy <type> <from> <to> <batchSize>')
|
||||
.version(packageJson.version)
|
||||
.description('Copy data from one instance to another')
|
||||
.option(
|
||||
'-s, --bulkSource <bulkSource>',
|
||||
'The source identifier for the bulk to use with the target instance [copy]',
|
||||
'copy',
|
||||
)
|
||||
// TODO: remove
|
||||
.option('-a, --appVersion <version>', 'The App version to use [unset by default]')
|
||||
.allowUnknownOption(false)
|
||||
.action(async (type, from, to, batchSize, copyCommand) => {
|
||||
// validate type
|
||||
if (typeof type !== 'string') {
|
||||
await Logger.error('expected parameter "type" to be of type: string');
|
||||
copyCommand.help();
|
||||
helpAndExit(copyCommand.helpInformation());
|
||||
}
|
||||
|
||||
let fromURL = '';
|
||||
let toURL = '';
|
||||
|
||||
// validate urls
|
||||
try {
|
||||
fromURL = new URL(from).toString();
|
||||
toURL = new URL(to).toString();
|
||||
} catch (error) {
|
||||
await Logger.error('expected parameters "from" and "to" to be valid urls', error);
|
||||
helpAndExit(copyCommand.helpInformation());
|
||||
}
|
||||
|
||||
// validate batchSize
|
||||
if (Number.isNaN(Number.parseInt(batchSize, 10))) {
|
||||
await Logger.error('expected parameter "batchSize" to be of type: number');
|
||||
helpAndExit(copyCommand.helpInformation());
|
||||
}
|
||||
|
||||
Logger.info(`Copying ${type} objects from ${fromURL} to ${toURL}`);
|
||||
|
||||
copy(client, {
|
||||
batchSize: Number.parseInt(batchSize, 10),
|
||||
from: fromURL,
|
||||
source: copyCommand.bulkSource,
|
||||
to: toURL,
|
||||
type: type as SCThingType,
|
||||
version: copyCommand.appVersion,
|
||||
}).then(
|
||||
() => {
|
||||
Logger.ok('Done');
|
||||
},
|
||||
error => {
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
commander.parse(process.argv);
|
||||
311
packages/api/src/client.ts
Normal file
311
packages/api/src/client.ts
Normal file
@@ -0,0 +1,311 @@
|
||||
/*
|
||||
* Copyright (C) 2018-2022 Open StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {
|
||||
SCAbstractRoute,
|
||||
SCErrorResponse,
|
||||
SCFeatureConfiguration,
|
||||
SCFeatureConfigurationPlugin,
|
||||
SCIndexRequest,
|
||||
SCIndexResponse,
|
||||
SCIndexRoute,
|
||||
SCInternalServerErrorResponse,
|
||||
SCMultiSearchRequest,
|
||||
SCMultiSearchResponse,
|
||||
SCMultiSearchRoute,
|
||||
SCNotFoundErrorResponse,
|
||||
SCRequests,
|
||||
SCSearchRequest,
|
||||
SCSearchResponse,
|
||||
SCSearchRoute,
|
||||
SCThings,
|
||||
} from '@openstapps/core';
|
||||
import {ApiError, CoreVersionIncompatibleError, OutOfRangeError, PluginNotAvailableError} from './errors';
|
||||
import {HttpClientHeaders, HttpClientInterface} from './http-client-interface';
|
||||
|
||||
/**
|
||||
* StApps-API client
|
||||
*/
|
||||
export class Client {
|
||||
/**
|
||||
* Instance of index route
|
||||
*/
|
||||
private readonly indexRoute = new SCIndexRoute();
|
||||
|
||||
/**
|
||||
* Instance of multi search request route
|
||||
*/
|
||||
private readonly multiSearchRoute = new SCMultiSearchRoute();
|
||||
|
||||
/**
|
||||
* Instance of search request route
|
||||
*/
|
||||
private readonly searchRoute = new SCSearchRoute();
|
||||
|
||||
/**
|
||||
* Features supported by backend
|
||||
*/
|
||||
private supportedFeatures?: SCFeatureConfiguration = undefined;
|
||||
|
||||
/**
|
||||
* Default headers
|
||||
*
|
||||
* TODO: remove headers
|
||||
*/
|
||||
protected readonly headers: HttpClientHeaders = {};
|
||||
|
||||
/**
|
||||
* Create a new search request with altered pagination parameters to move to the next result window
|
||||
*
|
||||
* @param searchRequest Last search request
|
||||
* @param searchResponse Search response for supplied search request
|
||||
* @throws OutOfRangeError Throws an error if the next window is beyond the total number of results
|
||||
*/
|
||||
static nextWindow(searchRequest: SCSearchRequest, searchResponse: SCSearchResponse): SCSearchRequest {
|
||||
// calculate next from
|
||||
const from = searchResponse.pagination.offset + searchResponse.pagination.count;
|
||||
|
||||
// throw an error if the next window is beyond the total number of results
|
||||
if (from >= searchResponse.pagination.total) {
|
||||
throw new OutOfRangeError(searchRequest);
|
||||
}
|
||||
|
||||
// return a search request with the next window
|
||||
return {
|
||||
...searchRequest,
|
||||
from,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiate a new StApps-API client to communicate with a StApps-backend.
|
||||
*
|
||||
* @param httpClient HTTP client to use
|
||||
* @param url URL of the backend
|
||||
* @param version App version to use when requesting data *(only necessary if URL is ambiguous)*
|
||||
*
|
||||
* TODO: remove headers/version
|
||||
*/
|
||||
constructor(protected httpClient: HttpClientInterface, protected url: string, protected version?: string) {
|
||||
// cut trailing slash if needed
|
||||
this.url = this.url.replace(/\/$/, '');
|
||||
|
||||
this.headers = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
if (typeof version === 'string') {
|
||||
this.headers['X-StApps-Version'] = this.version;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a thing by its UID
|
||||
*
|
||||
* @param uid UID of the thing to fetch
|
||||
*/
|
||||
async getThing(uid: string): Promise<SCThings> {
|
||||
const response = await this.search({
|
||||
filter: {
|
||||
arguments: {
|
||||
field: 'uid',
|
||||
value: uid,
|
||||
},
|
||||
type: 'value',
|
||||
},
|
||||
size: 1,
|
||||
});
|
||||
|
||||
if (response.data.length === 1 && response.data[0].uid === uid) {
|
||||
return response.data[0];
|
||||
}
|
||||
|
||||
throw new SCInternalServerErrorResponse(new SCNotFoundErrorResponse(true), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a handshake with the backend and check StAppsCore version
|
||||
*
|
||||
* @param coreVersion StAppsCore version to check
|
||||
*/
|
||||
async handshake(coreVersion: string): Promise<SCIndexResponse> {
|
||||
const request: SCIndexRequest = {};
|
||||
|
||||
const response = await this.invokeRoute<SCIndexResponse>(this.indexRoute, undefined, request);
|
||||
|
||||
if (response.backend.SCVersion.split('.')[0] !== coreVersion.split('.')[0]) {
|
||||
throw new CoreVersionIncompatibleError(coreVersion, response.backend.SCVersion);
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
this.supportedFeatures = response?.app?.features;
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke a plugin route
|
||||
*
|
||||
* @param name name of the plugin
|
||||
* @param parameters Parameters for the URL fragment
|
||||
* @param body Body for the request
|
||||
*/
|
||||
async invokePlugin<T>(name: string, parameters?: {[k: string]: string}, body?: SCRequests): Promise<T> {
|
||||
if (typeof this.supportedFeatures === 'undefined') {
|
||||
const request: SCIndexRequest = {};
|
||||
const response = await this.invokeRoute<SCIndexResponse>(this.indexRoute, undefined, request);
|
||||
if (typeof response?.app?.features !== 'undefined') {
|
||||
/* istanbul ignore next */
|
||||
this.supportedFeatures = response?.app?.features;
|
||||
}
|
||||
}
|
||||
const pluginInfo: SCFeatureConfigurationPlugin | undefined = this.supportedFeatures?.plugins?.[name];
|
||||
if (typeof pluginInfo === 'undefined') {
|
||||
throw new PluginNotAvailableError(name);
|
||||
}
|
||||
|
||||
const route = new SCIndexRoute();
|
||||
route.urlPath = pluginInfo.urlPath;
|
||||
|
||||
return this.invokeRoute<T>(route, parameters, body);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke a route
|
||||
*
|
||||
* @param route Route to invoke
|
||||
* @param parameters Parameters for the URL fragment
|
||||
* @param body Body for the request
|
||||
*/
|
||||
async invokeRoute<T>(
|
||||
route: SCAbstractRoute,
|
||||
parameters?: {[k: string]: string},
|
||||
body?: SCRequests,
|
||||
): Promise<T> {
|
||||
// make the request
|
||||
const response = await this.httpClient.request({
|
||||
body: body,
|
||||
// TODO: remove headers
|
||||
headers: this.headers,
|
||||
method: route.method,
|
||||
url: new URL(this.url + route.getUrlPath(parameters)),
|
||||
});
|
||||
|
||||
if (response.statusCode === route.statusCodeSuccess) {
|
||||
return response.body as T;
|
||||
}
|
||||
|
||||
throw new ApiError(response.body as SCErrorResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a multi search request to the backend
|
||||
*
|
||||
* All results will be returned for requests where no size is set.
|
||||
*
|
||||
* @param multiSearchRequest Multi search request
|
||||
*/
|
||||
async multiSearch(multiSearchRequest: SCMultiSearchRequest): Promise<SCMultiSearchResponse> {
|
||||
const preFlightRequest: SCMultiSearchRequest = {};
|
||||
let preFlightNecessary = false;
|
||||
|
||||
// gather search requests where size is not set
|
||||
for (const key of Object.keys(multiSearchRequest)) {
|
||||
const searchRequest = multiSearchRequest[key];
|
||||
|
||||
if (typeof searchRequest.size === 'undefined') {
|
||||
preFlightRequest[key] = {
|
||||
...searchRequest,
|
||||
};
|
||||
preFlightRequest[key].size = 0;
|
||||
preFlightNecessary = true;
|
||||
}
|
||||
}
|
||||
|
||||
let returnMultiSearchRequest = multiSearchRequest;
|
||||
|
||||
if (preFlightNecessary) {
|
||||
// copy multi search request
|
||||
returnMultiSearchRequest = {
|
||||
...multiSearchRequest,
|
||||
};
|
||||
|
||||
// make pre flight request
|
||||
const preFlightResponse = await this.invokeRoute<SCMultiSearchResponse>(
|
||||
this.multiSearchRoute,
|
||||
undefined,
|
||||
preFlightRequest,
|
||||
);
|
||||
|
||||
// set size for multi search requests that were in pre flight request
|
||||
for (const key of Object.keys(preFlightRequest)) {
|
||||
returnMultiSearchRequest[key].size = preFlightResponse[key].pagination.total;
|
||||
}
|
||||
}
|
||||
|
||||
// actually invoke the route
|
||||
return this.invokeRoute<SCMultiSearchResponse>(
|
||||
this.multiSearchRoute,
|
||||
undefined,
|
||||
returnMultiSearchRequest,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a search request to the backend
|
||||
*
|
||||
* All results will be returned if no size is set in the request.
|
||||
*
|
||||
* @param searchRequest Search request
|
||||
*/
|
||||
async search(searchRequest: SCSearchRequest): Promise<SCSearchResponse> {
|
||||
let size: number | undefined = searchRequest.size;
|
||||
|
||||
if (typeof size === 'undefined') {
|
||||
const preFlightResponse = await this.invokeRoute<SCSearchResponse>(this.searchRoute, undefined, {
|
||||
...searchRequest,
|
||||
size: 0,
|
||||
});
|
||||
|
||||
size = preFlightResponse.pagination.total;
|
||||
}
|
||||
|
||||
return this.invokeRoute<SCSearchResponse>(this.searchRoute, undefined, {
|
||||
...searchRequest,
|
||||
size,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the next search results
|
||||
*
|
||||
* @param searchRequest Last search request
|
||||
* @param searchResponse Search response for supplied search request
|
||||
*/
|
||||
async searchNext(
|
||||
searchRequest: SCSearchRequest,
|
||||
searchResponse: SCSearchResponse,
|
||||
): Promise<{
|
||||
/* tslint:disable:completed-docs */
|
||||
searchRequest: SCSearchRequest;
|
||||
searchResponse: SCSearchResponse;
|
||||
/* tslint:enable:completed-docs */
|
||||
}> {
|
||||
const nextSearchRequest = Client.nextWindow(searchRequest, searchResponse);
|
||||
|
||||
return {
|
||||
searchRequest: nextSearchRequest,
|
||||
searchResponse: await this.search(nextSearchRequest),
|
||||
};
|
||||
}
|
||||
}
|
||||
246
packages/api/src/connector-client.ts
Normal file
246
packages/api/src/connector-client.ts
Normal file
@@ -0,0 +1,246 @@
|
||||
/*
|
||||
* Copyright (C) 2019-2022 Open StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {asyncPool} from '@krlwlfrt/async-pool/lib/async-pool';
|
||||
import {
|
||||
isThing,
|
||||
SCAssociatedThingWithoutReferences,
|
||||
SCBulkResponse,
|
||||
SCBulkRoute,
|
||||
SCLicensePlate,
|
||||
SCNamespaces,
|
||||
SCThings,
|
||||
SCThingType,
|
||||
SCThingUpdateResponse,
|
||||
SCThingUpdateRoute,
|
||||
} from '@openstapps/core';
|
||||
import moment from 'moment';
|
||||
import clone = require('rfdc');
|
||||
import {v5} from 'uuid';
|
||||
import {Bulk} from './bulk';
|
||||
import {Client} from './client';
|
||||
import {EmptyBulkError, NamespaceNotDefinedError} from './errors';
|
||||
|
||||
/**
|
||||
* StApps-API client
|
||||
*/
|
||||
export class ConnectorClient extends Client {
|
||||
/**
|
||||
* The default timeout for the bulk to expire
|
||||
*/
|
||||
static readonly BULK_TIMEOUT = 3600;
|
||||
|
||||
/**
|
||||
* The limit of how many items should be indexed concurrently
|
||||
*/
|
||||
static readonly ITEM_CONCURRENT_LIMIT = 5;
|
||||
|
||||
/**
|
||||
* Instance of multi search request route
|
||||
*/
|
||||
private readonly bulkRoute = new SCBulkRoute();
|
||||
|
||||
/**
|
||||
* Instance of multi search request route
|
||||
*/
|
||||
private readonly thingUpdateRoute = new SCThingUpdateRoute();
|
||||
|
||||
/**
|
||||
* Make a UUID from a UID and a namespace ID
|
||||
*
|
||||
* Note: valid namespace IDs are license plates of StApps universities.
|
||||
* See documentation of `NAMESPACES` for valid namespace IDs.*
|
||||
*
|
||||
* @param uid UID to make UUID from
|
||||
* @param namespaceId Namespace ID to use to make UUID
|
||||
*/
|
||||
static makeUUID(uid: string, namespaceId: SCLicensePlate): string {
|
||||
if (typeof SCNamespaces[namespaceId] === 'undefined') {
|
||||
throw new NamespaceNotDefinedError(namespaceId);
|
||||
}
|
||||
|
||||
return v5(uid.toString(), SCNamespaces[namespaceId]!);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove fields from a thing that are references
|
||||
*
|
||||
* This effectively turns a thing into a thing without references, e.g. SCDish into SCDishWithoutReferences.
|
||||
*
|
||||
* @param thing Thing to remove references from
|
||||
*/
|
||||
static removeReferences<THING extends SCThings>(thing: THING): SCAssociatedThingWithoutReferences<THING> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const thingWithoutReferences = clone()<any>(thing);
|
||||
|
||||
delete thingWithoutReferences.origin;
|
||||
|
||||
// iterate over all properties
|
||||
for (const key in thingWithoutReferences) {
|
||||
/* istanbul ignore if */
|
||||
if (!thingWithoutReferences.hasOwnProperty(key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const property = thingWithoutReferences[key];
|
||||
|
||||
// check if property itself is a thing
|
||||
if (isThing(property)) {
|
||||
// delete said property
|
||||
delete thingWithoutReferences[key];
|
||||
continue;
|
||||
}
|
||||
|
||||
// check if property is an array
|
||||
if (Array.isArray(property)) {
|
||||
if (property.every(isThing)) {
|
||||
// delete property if every item in it is a thing
|
||||
delete thingWithoutReferences[key];
|
||||
} else {
|
||||
// check every item in array
|
||||
for (const item of property) {
|
||||
if (['boolean', 'number', 'string'].includes(typeof item)) {
|
||||
// skip primitives
|
||||
continue;
|
||||
}
|
||||
|
||||
// check every property
|
||||
for (const itemKey in item) {
|
||||
/* istanbul ignore if */
|
||||
if (!item.hasOwnProperty(itemKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isThing(item[itemKey])) {
|
||||
// delete properties that are things
|
||||
delete item[itemKey];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (typeof property === 'object') {
|
||||
// iterate over all properties in nested objects
|
||||
for (const nestedKey in property) {
|
||||
if (isThing(property[nestedKey])) {
|
||||
// delete properties that are things
|
||||
delete property[nestedKey];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return thingWithoutReferences as SCAssociatedThingWithoutReferences<THING>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively deletes all undefined properties from an object instance
|
||||
*
|
||||
* @param object Object to delete undefined properties from
|
||||
*/
|
||||
static removeUndefinedProperties(object: object): void {
|
||||
// return atomic data types and arrays (recursion anchor)
|
||||
if (typeof object !== 'object' || Array.isArray(object)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// check each key
|
||||
for (const key in object) {
|
||||
/* istanbul ignore if */
|
||||
if (!object.hasOwnProperty(key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const indexedObject = object as {[k: string]: unknown};
|
||||
|
||||
if (typeof indexedObject[key] === 'undefined') {
|
||||
// delete undefined keyss
|
||||
delete indexedObject[key];
|
||||
} else {
|
||||
// check recursive
|
||||
ConnectorClient.removeUndefinedProperties(indexedObject[key] as object);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request a bulk transfer to the backend
|
||||
*
|
||||
* This uses the Bulk API supplied by the backend and returns an object that can be used
|
||||
* just like the client itself, while handling the information necessary in bulk transfers.
|
||||
*
|
||||
* @param type StAppsCore thing type
|
||||
* @param source Source identifier (should be unique per actual data source)
|
||||
* @param timeout Timeout in seconds when the bulk should expire
|
||||
*/
|
||||
async bulk<T extends SCThings>(type: SCThingType, source: string, timeout?: number): Promise<Bulk<T>> {
|
||||
// set default value for timeout to one hour
|
||||
const bulkTimeout = typeof timeout !== 'number' ? ConnectorClient.BULK_TIMEOUT : timeout;
|
||||
|
||||
const bulkData = await this.invokeRoute<SCBulkResponse>(this.bulkRoute, undefined, {
|
||||
expiration: moment().add(bulkTimeout, 'seconds').format(),
|
||||
source: source,
|
||||
type: type,
|
||||
});
|
||||
|
||||
return new Bulk(type, this, bulkData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Index a list of things
|
||||
*
|
||||
* Note that source is optional but is set to `'stapps-api'` in that case.
|
||||
* This will override any previous bulk that you indexed with that source.
|
||||
*
|
||||
* @param things List of things to index
|
||||
* @param source Source of the things
|
||||
* @param timeout Timeout of the bulk in seconds
|
||||
* @see ConnectorClient.bulk
|
||||
*/
|
||||
async index<T extends SCThings>(things: T[], source?: string, timeout?: number): Promise<void> {
|
||||
// check that number of things is not zero
|
||||
if (things.length === 0) {
|
||||
throw new EmptyBulkError();
|
||||
}
|
||||
|
||||
// set default source if none is given
|
||||
const thingSource = typeof source === 'undefined' ? 'stapps-api' : source;
|
||||
|
||||
// request a new bulk
|
||||
const bulk = await this.bulk(things[0].type, thingSource, timeout);
|
||||
|
||||
// add items to the bulk - 5 concurrently
|
||||
await asyncPool(ConnectorClient.ITEM_CONCURRENT_LIMIT, things, thing => bulk.add(thing));
|
||||
|
||||
// close bulk
|
||||
await bulk.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing StAppsCore thing
|
||||
*
|
||||
* @param thing StAppsCore thing to update
|
||||
*/
|
||||
async update(thing: SCThings): Promise<SCThingUpdateResponse> {
|
||||
return this.invokeRoute<SCThingUpdateResponse>(
|
||||
this.thingUpdateRoute,
|
||||
{
|
||||
TYPE: encodeURIComponent(thing.type),
|
||||
UID: encodeURIComponent(thing.uid),
|
||||
},
|
||||
thing,
|
||||
);
|
||||
}
|
||||
}
|
||||
113
packages/api/src/copy.ts
Normal file
113
packages/api/src/copy.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Copyright (C) 2018-2022 Open StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {asyncPool} from '@krlwlfrt/async-pool/lib/async-pool';
|
||||
import {SCSearchRequest, SCThingType} from '@openstapps/core';
|
||||
import {Bar} from 'cli-progress';
|
||||
import {Client} from './client';
|
||||
import {ConnectorClient} from './connector-client';
|
||||
import {OutOfRangeError} from './errors';
|
||||
import {HttpClientInterface} from './http-client-interface';
|
||||
|
||||
/**
|
||||
* Options to set up copying data from one backend to another
|
||||
*/
|
||||
export interface CopyOptions {
|
||||
/**
|
||||
* Batch size to copy at once
|
||||
*/
|
||||
batchSize: number;
|
||||
|
||||
/**
|
||||
* URL of the backend to copy from
|
||||
*/
|
||||
from: string;
|
||||
|
||||
/**
|
||||
* Source identifier
|
||||
*/
|
||||
source: string;
|
||||
|
||||
/**
|
||||
* URL of the backend to copy to
|
||||
*/
|
||||
to: string;
|
||||
|
||||
/**
|
||||
* StAppsCore type to copy
|
||||
*/
|
||||
type: SCThingType;
|
||||
|
||||
/**
|
||||
* StApps version identifier to copy data for
|
||||
*/
|
||||
version: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy data for a StAppsCore type from one backend to another
|
||||
*
|
||||
* @param client HTTP client
|
||||
* @param options Map of options
|
||||
*/
|
||||
export async function copy(client: HttpClientInterface, options: CopyOptions): Promise<void> {
|
||||
const apiIn = new Client(client, options.from, options.version);
|
||||
const apiOut = new ConnectorClient(client, options.to);
|
||||
|
||||
// open a bulk
|
||||
const bulk = await apiOut.bulk(options.type, options.source);
|
||||
|
||||
let searchRequest: SCSearchRequest = {
|
||||
filter: {
|
||||
arguments: {
|
||||
field: 'type',
|
||||
value: options.type,
|
||||
},
|
||||
type: 'value',
|
||||
},
|
||||
size: 0,
|
||||
};
|
||||
|
||||
let searchResponse = await apiIn.search(searchRequest);
|
||||
|
||||
searchRequest.size = options.batchSize;
|
||||
|
||||
const progressBar = new Bar({});
|
||||
progressBar.start(searchResponse.pagination.total, 0);
|
||||
|
||||
let outOfRange = false;
|
||||
|
||||
do {
|
||||
try {
|
||||
({searchRequest, searchResponse} = await apiIn.searchNext(searchRequest, searchResponse));
|
||||
|
||||
await asyncPool(ConnectorClient.ITEM_CONCURRENT_LIMIT, searchResponse.data, async item => {
|
||||
progressBar.increment(1);
|
||||
|
||||
return bulk.add(item);
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof OutOfRangeError) {
|
||||
outOfRange = true;
|
||||
} else {
|
||||
progressBar.stop();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
} while (!outOfRange);
|
||||
|
||||
await bulk.done();
|
||||
|
||||
progressBar.stop();
|
||||
}
|
||||
166
packages/api/src/e2e.ts
Normal file
166
packages/api/src/e2e.ts
Normal file
@@ -0,0 +1,166 @@
|
||||
/*
|
||||
* Copyright (C) 2019-2022 Open StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
/* eslint-disable unicorn/prevent-abbreviations */
|
||||
|
||||
import {SCSearchRequest, SCThings, SCThingType} from '@openstapps/core';
|
||||
import {Logger} from '@openstapps/logger';
|
||||
import {deepStrictEqual} from 'assert';
|
||||
import {readdir, readFile} from 'fs';
|
||||
import path from 'path';
|
||||
import {promisify} from 'util';
|
||||
import {ConnectorClient} from './connector-client';
|
||||
import {HttpClientInterface} from './http-client-interface';
|
||||
|
||||
const localItemMap: Map<string, SCThings> = new Map();
|
||||
const remoteItemMap: Map<string, SCThings> = new Map();
|
||||
|
||||
/**
|
||||
* Options to set up indexing core test files to backend
|
||||
*/
|
||||
export interface E2EOptions {
|
||||
/**
|
||||
* File path of the directory containing core test files
|
||||
*/
|
||||
samplesLocation: string;
|
||||
|
||||
/**
|
||||
* URL of the backend to index to
|
||||
*/
|
||||
to: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function that can be used for integration tests.
|
||||
* Adds all the SCThings that getItemsFromSamples() returns to the backend.
|
||||
* Afterwards retrieves the items from backend and checks for differences with original ones.
|
||||
*/
|
||||
export async function e2eRun(client: HttpClientInterface, options: E2EOptions): Promise<void> {
|
||||
localItemMap.clear();
|
||||
remoteItemMap.clear();
|
||||
|
||||
const api = new ConnectorClient(client, options.to);
|
||||
try {
|
||||
await indexSamples(api, options);
|
||||
Logger.info(`All samples have been indexed via the backend`);
|
||||
|
||||
await retrieveItems(api);
|
||||
Logger.info(`All samples have been retrieved from the backend`);
|
||||
compareItems();
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retieves all samples previously index using the api
|
||||
*/
|
||||
async function retrieveItems(api: ConnectorClient): Promise<void> {
|
||||
const singleItemSearchRequest: SCSearchRequest = {
|
||||
filter: {
|
||||
arguments: {
|
||||
field: 'uid',
|
||||
value: 'replace-me',
|
||||
},
|
||||
type: 'value',
|
||||
},
|
||||
};
|
||||
for (const uid of localItemMap.keys()) {
|
||||
singleItemSearchRequest.filter!.arguments.value = uid;
|
||||
const searchResonse = await api.search(singleItemSearchRequest);
|
||||
if (searchResonse.data.length !== 1) {
|
||||
throw new Error(
|
||||
`Search for single SCThing with uid: ${uid} returned ${searchResonse.data.length} results`,
|
||||
);
|
||||
}
|
||||
remoteItemMap.set(uid, searchResonse.data[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares all samples (local and remote) with the same uid and throws if they're not deep equal
|
||||
*/
|
||||
function compareItems() {
|
||||
for (const localThing of localItemMap.values()) {
|
||||
/* istanbul ignore next retrieveItems will throw before*/
|
||||
if (!remoteItemMap.has(localThing.uid)) {
|
||||
throw new Error(`Did not retrieve expected SCThing with uid: ${localThing.uid}`);
|
||||
}
|
||||
const remoteThing = remoteItemMap.get(localThing.uid);
|
||||
deepStrictEqual(remoteThing, localThing, `Unexpected difference between original and retrieved sample`);
|
||||
}
|
||||
Logger.info(
|
||||
`All samples retrieved from the backend are the same (deep equal) as the original ones submitted`,
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Function to add all the SCThings that getItemsFromSamples() returns to the backend
|
||||
*/
|
||||
async function indexSamples(api: ConnectorClient, options: E2EOptions): Promise<void> {
|
||||
try {
|
||||
const items = await getItemsFromSamples(options.samplesLocation);
|
||||
|
||||
if (items.length === 0) {
|
||||
throw new Error('Could not index samples. None were retrieved from the file system.');
|
||||
}
|
||||
|
||||
// sort items by type
|
||||
const itemMap: Map<SCThingType, SCThings[]> = new Map();
|
||||
for (const item of items) {
|
||||
if (!itemMap.has(item.type)) {
|
||||
itemMap.set(item.type, []);
|
||||
}
|
||||
const itemsOfSameType = itemMap.get(item.type) as SCThings[];
|
||||
itemsOfSameType.push(item);
|
||||
itemMap.set(item.type, itemsOfSameType);
|
||||
localItemMap.set(item.uid, item);
|
||||
}
|
||||
// add items depending on their type property with one type per bulk
|
||||
for (const type of itemMap.keys()) {
|
||||
await api.index(itemMap.get(type) as SCThings[], 'stapps-core-sample-data');
|
||||
}
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all SCThings from the predefined core test json files
|
||||
*
|
||||
* @param samplesDirectory Filepath to the directory containing to the core test json files
|
||||
* @returns an Array of all the SCThings specified for test usage
|
||||
*/
|
||||
export async function getItemsFromSamples<T extends SCThings>(samplesDirectory: string): Promise<T[]> {
|
||||
const readDirPromised = promisify(readdir);
|
||||
const readFilePromised = promisify(readFile);
|
||||
|
||||
const things: T[] = [];
|
||||
try {
|
||||
const fileNames = await readDirPromised(samplesDirectory);
|
||||
for (const fileName of fileNames) {
|
||||
const filePath = path.join(samplesDirectory, fileName);
|
||||
if (filePath.endsWith('.json')) {
|
||||
const fileContent = await readFilePromised(filePath, {encoding: 'utf8'});
|
||||
const schemaObject = JSON.parse(fileContent);
|
||||
if (schemaObject.errorNames.length === 0 && typeof schemaObject.instance.type === 'string') {
|
||||
things.push(schemaObject.instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return things;
|
||||
}
|
||||
148
packages/api/src/errors.ts
Normal file
148
packages/api/src/errors.ts
Normal file
@@ -0,0 +1,148 @@
|
||||
/*
|
||||
* Copyright (C) 2018-2022 Open StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {SCErrorResponse, SCLicensePlate, SCSearchRequest, SCThings} from '@openstapps/core';
|
||||
|
||||
/**
|
||||
* An error that can occur in the StApps API
|
||||
*/
|
||||
export class ApiError extends Error {
|
||||
/**
|
||||
* Instantiate a new error
|
||||
*
|
||||
* @param data Representation of an error that happened in the backend
|
||||
*/
|
||||
constructor(protected data: Partial<SCErrorResponse>) {
|
||||
super(data.message);
|
||||
|
||||
if (typeof data.name === 'string') {
|
||||
this.name = data.name;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add additional data to the output of the error
|
||||
*/
|
||||
toString(): string {
|
||||
let string_ = super.toString();
|
||||
|
||||
// add additional data
|
||||
if (typeof this.data.additionalData !== 'undefined') {
|
||||
string_ += `\n\n${JSON.stringify(this.data.additionalData)}`;
|
||||
}
|
||||
|
||||
// add "remote" stack trace
|
||||
if (typeof this.data.stack !== 'undefined') {
|
||||
string_ += `\n\n${this.data.stack}`;
|
||||
}
|
||||
|
||||
return string_;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Error that is thrown if the next window is beyond the total number of results
|
||||
*/
|
||||
export class OutOfRangeError extends ApiError {
|
||||
/**
|
||||
* Instantiate a new error
|
||||
*
|
||||
* @param searchRequest Search request where window is out of range
|
||||
*/
|
||||
constructor(searchRequest: SCSearchRequest) {
|
||||
super({
|
||||
additionalData: searchRequest,
|
||||
message: 'The next window is beyond the total number of results.',
|
||||
name: 'OutOfRangeError',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Error that is thrown when a bulk is filled with things of multiple types
|
||||
*/
|
||||
export class BulkWithMultipleTypesError extends ApiError {
|
||||
/**
|
||||
* Instantiate a new error
|
||||
*
|
||||
* @param offendingThing Thing that has a different type than the previous things
|
||||
*/
|
||||
constructor(offendingThing: SCThings) {
|
||||
super({
|
||||
additionalData: offendingThing,
|
||||
message: 'A bulk can only contain one type of things!',
|
||||
name: 'BulkWithMultipleTypesError',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Error that is thrown when a bulk is empty
|
||||
*/
|
||||
export class EmptyBulkError extends ApiError {
|
||||
/**
|
||||
* Instantiate a new error
|
||||
*/
|
||||
constructor() {
|
||||
super({
|
||||
message: 'You can not fill a bulk with zero things.',
|
||||
name: 'EmptyBulkError',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Error that is thrown when there is no namespace for a license plate
|
||||
*/
|
||||
export class NamespaceNotDefinedError extends ApiError {
|
||||
/**
|
||||
* Instantiate a new error
|
||||
*/
|
||||
constructor(namespaceId: SCLicensePlate) {
|
||||
super({
|
||||
message: `'${namespaceId}' has no namespace defined`,
|
||||
name: 'NamespaceNotDefinedError',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Error that is thrown when API and backend StAppsCore versions are incompatible
|
||||
*/
|
||||
export class CoreVersionIncompatibleError extends ApiError {
|
||||
/**
|
||||
* Instantiate a new error
|
||||
*/
|
||||
constructor(localVersion: string, remoteVersion: string) {
|
||||
super({
|
||||
message: `Local StAppsCore version ${localVersion} is incompatible to remote version ${remoteVersion}.`,
|
||||
name: 'CoreVersionIncompatibleError',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Error that is thrown when API and backend StAppsCore versions are incompatible
|
||||
*/
|
||||
export class PluginNotAvailableError extends ApiError {
|
||||
/**
|
||||
* Instantiate a new error
|
||||
*/
|
||||
constructor(requestedPluginWithName: string) {
|
||||
super({
|
||||
message: `A plugin named ${requestedPluginWithName} is not available.`,
|
||||
name: 'PluginNotAvailable',
|
||||
});
|
||||
}
|
||||
}
|
||||
90
packages/api/src/http-client-interface.ts
Normal file
90
packages/api/src/http-client-interface.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* Copyright (C) 2019-2022 Open StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {SCErrorResponse, SCRequests, SCResponses} from '@openstapps/core';
|
||||
|
||||
/**
|
||||
* A HTTP client that can send requests for the StApps API
|
||||
*/
|
||||
export interface HttpClientInterface {
|
||||
/**
|
||||
* Send request
|
||||
*
|
||||
* @param request Request to send
|
||||
*/
|
||||
request<T extends SCResponses>(request: HttpClientRequest): Promise<HttpClientResponse<T>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A map of headers
|
||||
*/
|
||||
export interface HttpClientHeaders {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* A HTTP client request
|
||||
*/
|
||||
export interface HttpClientRequest {
|
||||
/**
|
||||
* Body of the request
|
||||
*
|
||||
* A body to send with the request.
|
||||
*/
|
||||
body?: SCRequests;
|
||||
|
||||
/**
|
||||
* Headers of the request
|
||||
*
|
||||
* A key-value-map of headers to send with the request.
|
||||
*/
|
||||
headers?: HttpClientHeaders;
|
||||
|
||||
/**
|
||||
* Method of the request
|
||||
*
|
||||
* Should default to 'GET' if nothing is specified.
|
||||
*/
|
||||
method?: 'GET' | 'POST' | 'PUT';
|
||||
|
||||
/**
|
||||
* URL of the request
|
||||
*
|
||||
* The url to send the request to.
|
||||
*/
|
||||
url: URL;
|
||||
}
|
||||
|
||||
/**
|
||||
* A HTTP client response
|
||||
*/
|
||||
export interface HttpClientResponse<T extends SCResponses> {
|
||||
/**
|
||||
* Body of the response
|
||||
*/
|
||||
body: T | SCErrorResponse;
|
||||
|
||||
/**
|
||||
* Headers of the response
|
||||
*
|
||||
* A key-value-map of headers of the response
|
||||
*/
|
||||
headers: HttpClientHeaders;
|
||||
|
||||
/**
|
||||
* Status code of the response
|
||||
*/
|
||||
statusCode: number;
|
||||
}
|
||||
86
packages/api/src/http-client.ts
Normal file
86
packages/api/src/http-client.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright (C) 2019-2022 Open StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import got, {OptionsOfJSONResponseBody, Response as GotResponse} from 'got';
|
||||
|
||||
/**
|
||||
* Request options that requires a url
|
||||
* Note: adjust request options of got library for backward compatibility
|
||||
*/
|
||||
export interface RequestOptions extends Omit<OptionsOfJSONResponseBody, 'json' | 'body'> {
|
||||
/**
|
||||
* Body of the request
|
||||
*/
|
||||
// TODO: Use a specific type?
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
body?: any;
|
||||
/**
|
||||
* Target URL of the request
|
||||
*/
|
||||
url: URL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Response with generic for the type of body that is returned from the request
|
||||
*/
|
||||
export interface Response<TYPE_OF_BODY> extends GotResponse {
|
||||
/**
|
||||
* Typed body of the response
|
||||
*/
|
||||
body: TYPE_OF_BODY;
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP client that is based on request
|
||||
*/
|
||||
export class HttpClient {
|
||||
/**
|
||||
* Make a request
|
||||
*
|
||||
* @param requestConfig Configuration of the request
|
||||
*/
|
||||
async request<TYPE_OF_BODY>(requestConfig: RequestOptions): Promise<Response<TYPE_OF_BODY>> {
|
||||
const parameters: OptionsOfJSONResponseBody = {
|
||||
followRedirect: true,
|
||||
method: 'GET',
|
||||
responseType: 'json',
|
||||
};
|
||||
|
||||
if (typeof requestConfig.body !== 'undefined') {
|
||||
parameters.json = requestConfig.body;
|
||||
}
|
||||
|
||||
if (typeof requestConfig.headers !== 'undefined') {
|
||||
parameters.headers = requestConfig.headers;
|
||||
}
|
||||
|
||||
if (typeof requestConfig.method !== 'undefined') {
|
||||
parameters.method = requestConfig.method;
|
||||
}
|
||||
let response: Response<TYPE_OF_BODY>;
|
||||
try {
|
||||
response = await got(requestConfig.url.toString(), parameters);
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
if (typeof (error as any).response === 'undefined') {
|
||||
throw error;
|
||||
}
|
||||
// if there is a response (e.g. response with statusCode 404 etc.) provide it
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
response = (error as any).response as Response<TYPE_OF_BODY>;
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
70
packages/api/src/plugin-client.ts
Normal file
70
packages/api/src/plugin-client.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* Copyright (C) 2019-2022 Open StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {SCPluginRegisterRequest, SCPluginRegisterRoute} from '@openstapps/core';
|
||||
import {ConnectorClient} from './connector-client';
|
||||
import {Plugin} from './plugin';
|
||||
|
||||
/**
|
||||
* The PluginClient for registering and unregistering HTTP Plugins
|
||||
*
|
||||
* It contains a lot of the boilerplate for creating plugins, and thus simplifies the creation of such.
|
||||
*/
|
||||
export class PluginClient extends ConnectorClient {
|
||||
/**
|
||||
* Register a plugin in the backend
|
||||
*
|
||||
* **This method automatically calls [[Plugin.start]]**
|
||||
* You need to call this method before you can do anything with the plugin. If you want to register the plugin again,
|
||||
* you might first want to inform yourself how the backend behaves in such cases TODO: add docs for this
|
||||
*
|
||||
* @param plugin The instance of the plugin you want to register
|
||||
*/
|
||||
async registerPlugin(plugin: Plugin) {
|
||||
const request: SCPluginRegisterRequest = {
|
||||
action: 'add',
|
||||
plugin: {
|
||||
address: plugin.fullUrl,
|
||||
name: plugin.name,
|
||||
requestSchema: plugin.requestSchema,
|
||||
responseSchema: plugin.responseSchema,
|
||||
route: plugin.route,
|
||||
},
|
||||
};
|
||||
await this.invokeRoute(new SCPluginRegisterRoute(), undefined, request);
|
||||
|
||||
// start the plugin we just registered
|
||||
plugin.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister a plugin from the backend
|
||||
*
|
||||
* **This method automatically calls [[Plugin.stop]]**
|
||||
* If you want to unregister your plugin for some reason, you can do so by calling this method.
|
||||
* Use with caution.*
|
||||
*
|
||||
* @param plugin The instance of the plugin you want to register
|
||||
*/
|
||||
async unregisterPlugin(plugin: Plugin) {
|
||||
const request: SCPluginRegisterRequest = {
|
||||
action: 'remove',
|
||||
route: plugin.route,
|
||||
};
|
||||
// stop the plugin we want to unregister
|
||||
plugin.stop();
|
||||
|
||||
await this.invokeRoute(new SCPluginRegisterRoute(), undefined, request);
|
||||
}
|
||||
}
|
||||
252
packages/api/src/plugin.ts
Normal file
252
packages/api/src/plugin.ts
Normal file
@@ -0,0 +1,252 @@
|
||||
/*
|
||||
* Copyright (C) 2019-2022 Open StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {Converter} from '@openstapps/core-tools/lib/schema';
|
||||
import {Logger} from '@openstapps/logger';
|
||||
import bodyParser from 'body-parser';
|
||||
import express from 'express';
|
||||
import * as http from 'http';
|
||||
import * as http2 from 'http2';
|
||||
import {JSONSchema7} from 'json-schema';
|
||||
import morgan from 'morgan';
|
||||
import ErrnoException = NodeJS.ErrnoException;
|
||||
|
||||
/**
|
||||
* The Plugin for creating HTTP backend plugins
|
||||
*
|
||||
* It contains a lot of the boilerplate for creating plugins, and thus simplifies the creation of such.
|
||||
* To create your own plugin, you need to extend this class and implement the [[Plugin.onRouteInvoke]] method
|
||||
*/
|
||||
export abstract class Plugin {
|
||||
/**
|
||||
* The express instance
|
||||
*/
|
||||
private readonly app = express();
|
||||
|
||||
/**
|
||||
* The HTTP server
|
||||
*/
|
||||
private readonly server: http.Server;
|
||||
|
||||
/**
|
||||
* Whether the server is active or not
|
||||
*
|
||||
* When active is false, it will return 404 on all routes.
|
||||
*/
|
||||
protected active = false;
|
||||
|
||||
/**
|
||||
* The full URL of the plugin
|
||||
*
|
||||
* The full URL of the plugin consists out of URL:PORT
|
||||
*/
|
||||
public get fullUrl() {
|
||||
return `${this.url}:${this.port}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The port on which the plugin will listen on
|
||||
*/
|
||||
public port: string | number | false;
|
||||
|
||||
/**
|
||||
* The schema of the request interfaces defined by the user
|
||||
*/
|
||||
public readonly requestSchema: JSONSchema7 = {};
|
||||
|
||||
/**
|
||||
* The schema of the response interfaces defined by the user
|
||||
*/
|
||||
public readonly responseSchema: JSONSchema7 = {};
|
||||
|
||||
/**
|
||||
* Normalize a port into a number, string, or false.
|
||||
*
|
||||
* @param value the port you want to normalize
|
||||
*/
|
||||
protected static normalizePort(value: string) {
|
||||
const portNumber = Number.parseInt(value, 10);
|
||||
|
||||
/* istanbul ignore next */
|
||||
if (Number.isNaN(portNumber)) {
|
||||
// named pipe
|
||||
/* istanbul ignore next */
|
||||
return value;
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
if (portNumber >= 0) {
|
||||
// port number
|
||||
return portNumber;
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of the PluginClient
|
||||
*
|
||||
* Don't forget to call [[PluginClient.registerPlugin]]!
|
||||
* Refer to the examples for how to use the schemas. TODO: examples
|
||||
*
|
||||
* @param port The port of the plugin
|
||||
* @param name The name of the plugin
|
||||
* @param url The url of the plugin without the port or anything else, for example `http://localhost`
|
||||
* @param route The desired route that will be registered in the backend
|
||||
* @param backendUrl The url of the backend
|
||||
* @param converter If you want to use an already existing converter, you can pass it here
|
||||
* @param requestName the name of the request schema
|
||||
* @param responseName the name of the response schema
|
||||
* @param version the version. You should retrieve it from the package.json
|
||||
*/
|
||||
constructor(
|
||||
port: number,
|
||||
public name: string,
|
||||
public url: string,
|
||||
public route: string,
|
||||
protected backendUrl: string,
|
||||
converter: Converter,
|
||||
requestName: string,
|
||||
responseName: string,
|
||||
version: string,
|
||||
) {
|
||||
this.app.use(bodyParser.json());
|
||||
this.port = Plugin.normalizePort(
|
||||
/* istanbul ignore next */
|
||||
typeof process.env.PORT !== 'undefined' ? process.env.PORT : port.toString(),
|
||||
);
|
||||
this.app.set('port', this.port);
|
||||
|
||||
// setup express
|
||||
this.server = http.createServer(this.app);
|
||||
this.server.listen(this.port);
|
||||
/* istanbul ignore next */
|
||||
this.server.on('error', error => {
|
||||
/* istanbul ignore next */
|
||||
this.onError(error);
|
||||
});
|
||||
this.server.on('listening', () => {
|
||||
this.onListening();
|
||||
});
|
||||
|
||||
this.requestSchema = converter.getSchema(requestName, version);
|
||||
this.responseSchema = converter.getSchema(responseName, version);
|
||||
|
||||
this.app.use(morgan('dev'));
|
||||
|
||||
this.app.set('env', process.env.NODE_ENV);
|
||||
|
||||
this.app.all('*', async (request: express.Request, response: express.Response) => {
|
||||
if (this.active) {
|
||||
await this.onRouteInvoke(request, response);
|
||||
} else {
|
||||
response.status(http2.constants.HTTP_STATUS_NOT_FOUND);
|
||||
response.send();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Event listener for HTTP server "error" event.
|
||||
*
|
||||
* @param error The error that occurred
|
||||
*/
|
||||
|
||||
/* istanbul ignore next */
|
||||
private onError(error: ErrnoException) {
|
||||
if (error.syscall !== 'listen') {
|
||||
throw error;
|
||||
}
|
||||
|
||||
const bind = typeof this.port === 'string' ? `Pipe ${this.port}` : `Port ${this.port}`;
|
||||
|
||||
// handle specific listen errors with friendly messages
|
||||
switch (error.code) {
|
||||
case 'EACCES':
|
||||
// tslint:disable-next-line:no-floating-promises
|
||||
Logger.error(`${bind} requires elevated privileges`);
|
||||
process.exit(1);
|
||||
break;
|
||||
case 'EADDRINUSE':
|
||||
// tslint:disable-next-line:no-floating-promises
|
||||
Logger.error(`${bind} is already in use`);
|
||||
process.exit(1);
|
||||
break;
|
||||
default:
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Event listener for HTTP server "listening" event.
|
||||
*/
|
||||
private onListening() {
|
||||
const addr = this.server.address();
|
||||
/* istanbul ignore next */
|
||||
const bind = typeof addr === 'string' ? `pipe ${addr}` : addr === null ? 'null' : `port ${addr.port}`;
|
||||
Logger.ok(`Listening on ${bind}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* When the route gets invoked
|
||||
*
|
||||
* Override this method for your own plugin
|
||||
*
|
||||
* @param request An express Request from the backend
|
||||
* @param response An express Response to the backend for you to send back data
|
||||
*/
|
||||
protected abstract onRouteInvoke(request: express.Request, response: express.Response): Promise<void>;
|
||||
|
||||
/**
|
||||
* Closes the server
|
||||
*
|
||||
* This will stop the plugin from listening to any requests at all, and is currently an irreversible process.
|
||||
* This means, that the instantiated plugin is basically useless afterwards.
|
||||
*/
|
||||
public async close() {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.server.close(error => {
|
||||
/* istanbul ignore next */
|
||||
if (typeof error !== 'undefined') {
|
||||
/* istanbul ignore next */
|
||||
reject(error);
|
||||
}
|
||||
resolve(undefined);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the plugin
|
||||
*
|
||||
* **THIS METHOD GETS CALLED AUTOMATICALLY WITH [[PluginClient.registerPlugin]]**
|
||||
* If the plugin is not started, it will return 404 on any route
|
||||
*/
|
||||
public start() {
|
||||
this.active = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the plugin
|
||||
*
|
||||
* **THIS METHOD GETS CALLED AUTOMATICALLY WITH [[PluginClient.unregisterPlugin]]**
|
||||
* If the plugin is not started, it will return 404 on any route
|
||||
*/
|
||||
public stop() {
|
||||
// you can't unregister routes from express. So this is a workaround.
|
||||
this.active = false;
|
||||
}
|
||||
}
|
||||
148
packages/api/test/bulk.spec.ts
Normal file
148
packages/api/test/bulk.spec.ts
Normal file
@@ -0,0 +1,148 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {SCBulkAddRoute, SCBulkDoneRoute, SCDish, SCMessage, SCThingOriginType, SCThingType} from '@openstapps/core';
|
||||
import {expect} from 'chai';
|
||||
import chai from 'chai';
|
||||
import chaiAsPromised from 'chai-as-promised';
|
||||
import chaiSpies from 'chai-spies';
|
||||
import {suite, test} from '@testdeck/mocha';
|
||||
import moment from 'moment';
|
||||
import {Bulk} from '../src/bulk';
|
||||
import {Client} from '../src/client';
|
||||
import {BulkWithMultipleTypesError} from '../src/errors';
|
||||
import {HttpClient} from '../src/http-client';
|
||||
|
||||
chai.should();
|
||||
chai.use(chaiSpies);
|
||||
chai.use(chaiAsPromised);
|
||||
|
||||
const sandbox = chai.spy.sandbox();
|
||||
|
||||
const bulkAddRoute = new SCBulkAddRoute();
|
||||
const bulkDoneRoute = new SCBulkDoneRoute();
|
||||
|
||||
const httpClient = new HttpClient();
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
|
||||
@suite()
|
||||
export class BulkSpec {
|
||||
@test
|
||||
async add() {
|
||||
sandbox.on(client, 'invokeRoute', () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
expect(client.invokeRoute).not.to.have.been.called();
|
||||
|
||||
const bulk = new Bulk(SCThingType.Dish, client, {
|
||||
expiration: moment().add(3600, 'seconds').format(),
|
||||
source: 'foo',
|
||||
state: 'in progress',
|
||||
type: SCThingType.Dish,
|
||||
uid: 'bar',
|
||||
});
|
||||
|
||||
const dish: SCDish = {
|
||||
categories: [
|
||||
'main dish',
|
||||
],
|
||||
name: 'foobar',
|
||||
origin: {
|
||||
indexed: moment().format(),
|
||||
name: 'bar',
|
||||
type: SCThingOriginType.Remote,
|
||||
},
|
||||
type: SCThingType.Dish,
|
||||
uid: 'foo',
|
||||
};
|
||||
|
||||
await bulk.add(dish);
|
||||
|
||||
expect(client.invokeRoute).to.have.been.first.called.with(bulkAddRoute, {
|
||||
UID: 'bar',
|
||||
}, dish);
|
||||
}
|
||||
|
||||
@test
|
||||
async addFails() {
|
||||
const bulk = new Bulk(SCThingType.Dish, client, {
|
||||
expiration: moment().add(3600, 'seconds').format(),
|
||||
source: 'foo',
|
||||
state: 'in progress',
|
||||
type: SCThingType.Dish,
|
||||
uid: 'bar',
|
||||
});
|
||||
|
||||
const message: SCMessage = {
|
||||
audiences: [
|
||||
'students',
|
||||
],
|
||||
categories: [
|
||||
'news'
|
||||
],
|
||||
messageBody: 'Lorem ipsum.',
|
||||
name: 'foobar',
|
||||
origin: {
|
||||
indexed: moment().format(),
|
||||
name: 'bar',
|
||||
type: SCThingOriginType.Remote,
|
||||
},
|
||||
type: SCThingType.Message,
|
||||
uid: 'foo',
|
||||
};
|
||||
|
||||
return bulk.add(message).should.be.rejectedWith(BulkWithMultipleTypesError);
|
||||
}
|
||||
|
||||
async after() {
|
||||
sandbox.restore();
|
||||
}
|
||||
|
||||
@test
|
||||
async construct() {
|
||||
expect(() => {
|
||||
return new Bulk(SCThingType.Dish, client, {
|
||||
expiration: moment().add(3600, 'seconds').format(),
|
||||
source: 'foo',
|
||||
state: 'in progress',
|
||||
type: SCThingType.Dish,
|
||||
uid: 'bar',
|
||||
});
|
||||
}).not.to.throw();
|
||||
}
|
||||
|
||||
@test
|
||||
async done() {
|
||||
sandbox.on(client, 'invokeRoute', () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
expect(client.invokeRoute).not.to.have.been.called();
|
||||
|
||||
const bulk = new Bulk(SCThingType.Dish, client, {
|
||||
expiration: moment().add(3600, 'seconds').format(),
|
||||
source: 'foo',
|
||||
state: 'in progress',
|
||||
type: SCThingType.Dish,
|
||||
uid: 'bar',
|
||||
});
|
||||
|
||||
await bulk.done();
|
||||
|
||||
expect(client.invokeRoute).to.have.been.first.called.with(bulkDoneRoute, {
|
||||
UID: 'bar',
|
||||
});
|
||||
}
|
||||
}
|
||||
632
packages/api/test/client.spec.ts
Normal file
632
packages/api/test/client.spec.ts
Normal file
@@ -0,0 +1,632 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {
|
||||
SCIndexResponse,
|
||||
SCIndexRoute,
|
||||
SCMessage,
|
||||
SCMultiSearchResponse,
|
||||
SCMultiSearchRoute,
|
||||
SCSearchRequest,
|
||||
SCSearchResponse,
|
||||
SCSearchRoute,
|
||||
SCThingOriginType,
|
||||
SCThingType,
|
||||
} from '@openstapps/core';
|
||||
import {expect} from 'chai';
|
||||
import chai from 'chai';
|
||||
import chaiAsPromised from 'chai-as-promised';
|
||||
import chaiSpies from 'chai-spies';
|
||||
import {suite, test} from '@testdeck/mocha';
|
||||
import {Client} from '../src/client';
|
||||
import {ApiError, OutOfRangeError} from '../src/errors';
|
||||
import {HttpClient} from '../src/http-client';
|
||||
import {HttpClientResponse} from '../src/http-client-interface';
|
||||
|
||||
chai.should();
|
||||
chai.use(chaiSpies);
|
||||
chai.use(chaiAsPromised);
|
||||
|
||||
const sandbox = chai.spy.sandbox();
|
||||
|
||||
const indexRoute = new SCIndexRoute();
|
||||
const multiSearchRoute = new SCMultiSearchRoute();
|
||||
const searchRoute = new SCSearchRoute();
|
||||
|
||||
const httpClient = new HttpClient();
|
||||
|
||||
/**
|
||||
* Recursive Partial
|
||||
*
|
||||
* @see https://stackoverflow.com/a/51365037
|
||||
*/
|
||||
export type RecursivePartial<T> = {
|
||||
[P in keyof T]?:
|
||||
T[P] extends Array<(infer U)> ? Array<RecursivePartial<U>> :
|
||||
T[P] extends object ? RecursivePartial<T[P]> :
|
||||
T[P];
|
||||
};
|
||||
|
||||
async function invokeIndexRoute(): Promise<RecursivePartial<HttpClientResponse<SCIndexResponse>>> {
|
||||
return {
|
||||
body: {
|
||||
app: {
|
||||
features: {},
|
||||
},
|
||||
backend: {
|
||||
SCVersion: 'foo.bar.dummy',
|
||||
},
|
||||
},
|
||||
statusCode: indexRoute.statusCodeSuccess,
|
||||
};
|
||||
}
|
||||
|
||||
async function invokeIndexRouteFails(): Promise<RecursivePartial<HttpClientResponse<SCIndexResponse>>> {
|
||||
return {
|
||||
body: {
|
||||
backend: {
|
||||
SCVersion: 'foo.bar.dummy',
|
||||
},
|
||||
},
|
||||
statusCode: indexRoute.statusCodeSuccess + 1,
|
||||
};
|
||||
}
|
||||
|
||||
@suite()
|
||||
export class ClientSpec {
|
||||
async after() {
|
||||
sandbox.restore();
|
||||
}
|
||||
|
||||
@test
|
||||
async construct() {
|
||||
expect(() => {
|
||||
return new Client(httpClient, 'http://localhost');
|
||||
}).not.to.throw();
|
||||
}
|
||||
|
||||
@test
|
||||
async constructWithHeaders() {
|
||||
sandbox.on(httpClient, 'request', invokeIndexRoute);
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
|
||||
const client = new Client(httpClient, 'http://localhost', 'foo.foo.foo');
|
||||
await client.handshake('foo.bar.dummy');
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: {},
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-StApps-Version': 'foo.foo.foo',
|
||||
},
|
||||
method: indexRoute.method,
|
||||
url: new URL('http://localhost' + indexRoute.getUrlPath()),
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
async getThing() {
|
||||
const message: SCMessage = {
|
||||
audiences: [
|
||||
'employees',
|
||||
],
|
||||
categories: [
|
||||
'news'
|
||||
],
|
||||
messageBody: 'Lorem ipsum.',
|
||||
name: 'foo',
|
||||
origin: {
|
||||
indexed: 'foo',
|
||||
name: 'foo',
|
||||
type: SCThingOriginType.Remote,
|
||||
},
|
||||
type: SCThingType.Message,
|
||||
uid: 'foo',
|
||||
};
|
||||
|
||||
sandbox.on(httpClient, 'request', async (): Promise<HttpClientResponse<SCSearchResponse>> => {
|
||||
return {
|
||||
body: {
|
||||
data: [message],
|
||||
facets: [],
|
||||
pagination: {
|
||||
count: 0,
|
||||
offset: 0,
|
||||
total: 0,
|
||||
},
|
||||
stats: {
|
||||
time: 0,
|
||||
},
|
||||
},
|
||||
headers: {},
|
||||
statusCode: searchRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
await client.getThing('foo');
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: {
|
||||
filter: {
|
||||
arguments: {
|
||||
field: 'uid',
|
||||
value: 'foo',
|
||||
},
|
||||
type: 'value',
|
||||
},
|
||||
size: 1,
|
||||
},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: searchRoute.method,
|
||||
url: new URL('http://localhost' + searchRoute.getUrlPath()),
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
async getThingFailsByEmptyResponse() {
|
||||
sandbox.on(httpClient, 'request', async (): Promise<HttpClientResponse<SCSearchResponse>> => {
|
||||
return {
|
||||
body: {
|
||||
data: [],
|
||||
facets: [],
|
||||
pagination: {
|
||||
count: 0,
|
||||
offset: 0,
|
||||
total: 0,
|
||||
},
|
||||
stats: {
|
||||
time: 0,
|
||||
},
|
||||
},
|
||||
headers: {},
|
||||
statusCode: searchRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
|
||||
return client.getThing('bar').should.be.rejected;
|
||||
}
|
||||
|
||||
@test
|
||||
async getThingFailsByUid() {
|
||||
const message: SCMessage = {
|
||||
audiences: [
|
||||
'employees',
|
||||
],
|
||||
categories: [
|
||||
'news'
|
||||
],
|
||||
messageBody: 'Lorem ipsum.',
|
||||
name: 'foo',
|
||||
origin: {
|
||||
indexed: 'foo',
|
||||
name: 'foo',
|
||||
type: SCThingOriginType.Remote,
|
||||
},
|
||||
type: SCThingType.Message,
|
||||
uid: 'foo',
|
||||
};
|
||||
|
||||
sandbox.on(httpClient, 'request', async (): Promise<HttpClientResponse<SCSearchResponse>> => {
|
||||
return {
|
||||
body: {
|
||||
data: [message],
|
||||
facets: [],
|
||||
pagination: {
|
||||
count: 0,
|
||||
offset: 0,
|
||||
total: 0,
|
||||
},
|
||||
stats: {
|
||||
time: 0,
|
||||
},
|
||||
},
|
||||
headers: {},
|
||||
statusCode: searchRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
|
||||
return client.getThing('bar').should.be.rejected;
|
||||
}
|
||||
|
||||
@test
|
||||
async handshake() {
|
||||
sandbox.on(httpClient, 'request', invokeIndexRoute);
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
await client.handshake('foo.bar.dummy');
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: {},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: indexRoute.method,
|
||||
url: new URL('http://localhost' + indexRoute.getUrlPath()),
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
async handshakeFails() {
|
||||
sandbox.on(httpClient, 'request', invokeIndexRoute);
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
|
||||
return client.handshake('bar.bar.dummy').should.be.rejectedWith(ApiError);
|
||||
}
|
||||
|
||||
@test
|
||||
async invokePlugin() {
|
||||
sandbox.on(httpClient, 'request', async(): Promise<RecursivePartial<HttpClientResponse<SCIndexResponse>>> => {
|
||||
return {
|
||||
body: {
|
||||
app: {
|
||||
features: {
|
||||
plugins: {
|
||||
"supportedPlugin": { urlPath: "/" }
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
statusCode: indexRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
|
||||
await client.invokePlugin('unsupportedPlugin').should.be.rejectedWith(ApiError,/.*supportedPlugin.*/gmi);
|
||||
|
||||
// again with cached feature definitions
|
||||
return client.invokePlugin('supportedPlugin')
|
||||
.should.not.be.rejectedWith(ApiError,/.*supportedPlugin.*/gmi);
|
||||
}
|
||||
|
||||
@test
|
||||
async invokePluginUnavailable() {
|
||||
sandbox.on(httpClient, 'request', async(): Promise<RecursivePartial<HttpClientResponse<SCIndexResponse>>> => {
|
||||
return {
|
||||
body: {},
|
||||
statusCode: indexRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
|
||||
await client.invokePlugin('supportedPlugin').should.be.rejectedWith(ApiError,/.*supportedPlugin.*/gmi);
|
||||
|
||||
sandbox.restore();
|
||||
sandbox.on(httpClient, 'request', async(): Promise<RecursivePartial<HttpClientResponse<SCIndexResponse>>> => {
|
||||
return {
|
||||
body: {
|
||||
app: {
|
||||
features: {
|
||||
plugins: {
|
||||
'unsupportedPlugin': {
|
||||
urlPath: '/unsupported-plugin'
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
statusCode: indexRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
// again with cached feature definitions
|
||||
return client.invokePlugin('supportedPlugin')
|
||||
.should.be.rejectedWith(ApiError,/.*supportedPlugin.*/gmi);
|
||||
}
|
||||
|
||||
@test
|
||||
async invokeRoute() {
|
||||
sandbox.on(httpClient, 'request', invokeIndexRoute);
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
await client.invokeRoute(indexRoute);
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: undefined,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: indexRoute.method,
|
||||
url: new URL('http://localhost' + indexRoute.getUrlPath()),
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
async invokeRouteFails() {
|
||||
sandbox.on(httpClient, 'request', invokeIndexRouteFails);
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
|
||||
return client.invokeRoute(indexRoute).should.be.rejectedWith(ApiError);
|
||||
}
|
||||
|
||||
@test
|
||||
async multiSearch() {
|
||||
sandbox.on(httpClient, 'request', async (): Promise<HttpClientResponse<SCMultiSearchResponse>> => {
|
||||
return {
|
||||
body: {
|
||||
a: {
|
||||
data: [],
|
||||
facets: [],
|
||||
pagination: {
|
||||
count: 0,
|
||||
offset: 0,
|
||||
total: 0,
|
||||
},
|
||||
stats: {
|
||||
time: 0,
|
||||
},
|
||||
},
|
||||
b: {
|
||||
data: [],
|
||||
facets: [],
|
||||
pagination: {
|
||||
count: 0,
|
||||
offset: 0,
|
||||
total: 0,
|
||||
},
|
||||
stats: {
|
||||
time: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
headers: {},
|
||||
statusCode: searchRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
await client.multiSearch({a: {size: 1}, b: {size: 1}});
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: {a: {size: 1}, b: {size: 1}},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: multiSearchRoute.method,
|
||||
url: new URL('http://localhost' + multiSearchRoute.getUrlPath()),
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
async multiSearchWithPreflight() {
|
||||
sandbox.on(httpClient, 'request', async (): Promise<HttpClientResponse<SCMultiSearchResponse>> => {
|
||||
return {
|
||||
body: {
|
||||
bar: {
|
||||
data: [],
|
||||
facets: [],
|
||||
pagination: {
|
||||
count: 0,
|
||||
offset: 0,
|
||||
total: 500,
|
||||
},
|
||||
stats: {
|
||||
time: 0,
|
||||
},
|
||||
},
|
||||
foo: {
|
||||
data: [],
|
||||
facets: [],
|
||||
pagination: {
|
||||
count: 0,
|
||||
offset: 0,
|
||||
total: 1000,
|
||||
},
|
||||
stats: {
|
||||
time: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
headers: {},
|
||||
statusCode: searchRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
await client.multiSearch({foo: {}, bar: {}, foobar: {size: 30}});
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: {foo: {size: 0}, bar: {size: 0}},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: multiSearchRoute.method,
|
||||
url: new URL('http://localhost' + multiSearchRoute.getUrlPath()),
|
||||
});
|
||||
expect(httpClient.request).to.have.been.second.called.with({
|
||||
body: {foo: {size: 1000}, bar: {size: 500}, foobar: {size: 30}},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: multiSearchRoute.method,
|
||||
url: new URL('http://localhost' + multiSearchRoute.getUrlPath()),
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
nextWindow() {
|
||||
let searchRequest: SCSearchRequest = {size: 30};
|
||||
const searchResponse: SCSearchResponse = {
|
||||
data: [],
|
||||
facets: [],
|
||||
pagination: {
|
||||
count: 30,
|
||||
offset: 0,
|
||||
total: 60,
|
||||
},
|
||||
stats: {
|
||||
time: 0,
|
||||
},
|
||||
};
|
||||
|
||||
searchRequest = Client.nextWindow(searchRequest, searchResponse);
|
||||
|
||||
expect(searchRequest.from).to.equal(30);
|
||||
|
||||
searchResponse.pagination.offset = 30;
|
||||
|
||||
expect(() => {
|
||||
Client.nextWindow(searchRequest, searchResponse);
|
||||
}).to.throw(OutOfRangeError);
|
||||
}
|
||||
|
||||
@test
|
||||
async search() {
|
||||
sandbox.on(httpClient, 'request', async (): Promise<HttpClientResponse<SCSearchResponse>> => {
|
||||
return {
|
||||
body: {
|
||||
data: [],
|
||||
facets: [],
|
||||
pagination: {
|
||||
count: 0,
|
||||
offset: 0,
|
||||
total: 0,
|
||||
},
|
||||
stats: {
|
||||
time: 0,
|
||||
},
|
||||
},
|
||||
headers: {},
|
||||
statusCode: searchRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
await client.search({size: 1});
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: {size: 1},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: searchRoute.method,
|
||||
url: new URL('http://localhost' + searchRoute.getUrlPath()),
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
async searchNext() {
|
||||
const searchResponse: SCSearchResponse = {
|
||||
data: [],
|
||||
facets: [],
|
||||
pagination: {
|
||||
count: 30,
|
||||
offset: 0,
|
||||
total: 60,
|
||||
},
|
||||
stats: {
|
||||
time: 0,
|
||||
},
|
||||
};
|
||||
|
||||
sandbox.on(httpClient, 'request', async (): Promise<HttpClientResponse<SCSearchResponse>> => {
|
||||
return {
|
||||
body: searchResponse,
|
||||
headers: {},
|
||||
statusCode: searchRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
await client.searchNext({from: 0, size: 30}, searchResponse);
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: {from: 30, size: 30},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: searchRoute.method,
|
||||
url: new URL('http://localhost' + searchRoute.getUrlPath()),
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
async searchWithPreflight() {
|
||||
sandbox.on(httpClient, 'request', async (): Promise<HttpClientResponse<SCSearchResponse>> => {
|
||||
return {
|
||||
body: {
|
||||
data: [],
|
||||
facets: [],
|
||||
pagination: {
|
||||
count: 0,
|
||||
offset: 0,
|
||||
total: 1000,
|
||||
},
|
||||
stats: {
|
||||
time: 0,
|
||||
},
|
||||
},
|
||||
headers: {},
|
||||
statusCode: searchRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.first.called();
|
||||
|
||||
const client = new Client(httpClient, 'http://localhost');
|
||||
await client.search({});
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: {size: 0},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: searchRoute.method,
|
||||
url: new URL('http://localhost' + searchRoute.getUrlPath()),
|
||||
});
|
||||
expect(httpClient.request).to.have.been.second.called.with({
|
||||
body: {size: 1000},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: searchRoute.method,
|
||||
url: new URL('http://localhost' + searchRoute.getUrlPath()),
|
||||
});
|
||||
}
|
||||
}
|
||||
466
packages/api/test/connector-client.spec.ts
Normal file
466
packages/api/test/connector-client.spec.ts
Normal file
@@ -0,0 +1,466 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {asyncPool} from '@krlwlfrt/async-pool/lib/async-pool';
|
||||
import {
|
||||
isThing,
|
||||
SCBulkAddResponse,
|
||||
SCBulkAddRoute,
|
||||
SCBulkDoneResponse,
|
||||
SCBulkDoneRoute,
|
||||
SCBulkResponse,
|
||||
SCBulkRoute,
|
||||
SCMessage,
|
||||
SCThingOriginType,
|
||||
SCThingType,
|
||||
SCThingUpdateResponse,
|
||||
SCThingUpdateRoute,
|
||||
SCThingWithoutReferences,
|
||||
} from '@openstapps/core';
|
||||
import chai from 'chai';
|
||||
import {expect} from 'chai';
|
||||
import chaiAsPromised from 'chai-as-promised';
|
||||
import chaiSpies from 'chai-spies';
|
||||
import clone = require('rfdc');
|
||||
import {readdir, readFile} from 'fs';
|
||||
import {suite, test} from '@testdeck/mocha';
|
||||
import moment from 'moment';
|
||||
import {join, resolve} from 'path';
|
||||
import traverse from 'traverse';
|
||||
import {promisify} from 'util';
|
||||
import {ConnectorClient} from '../src/connector-client';
|
||||
import {EmptyBulkError, NamespaceNotDefinedError} from '../src/errors';
|
||||
import {HttpClient} from '../src/http-client';
|
||||
import {HttpClientRequest, HttpClientResponse} from '../src/http-client-interface';
|
||||
|
||||
chai.should();
|
||||
chai.use(chaiSpies);
|
||||
chai.use(chaiAsPromised);
|
||||
|
||||
const sandbox = chai.spy.sandbox();
|
||||
|
||||
const bulkAddRoute = new SCBulkAddRoute();
|
||||
const bulkDoneRoute = new SCBulkDoneRoute();
|
||||
const bulkRoute = new SCBulkRoute();
|
||||
const thingUpdateRoute = new SCThingUpdateRoute();
|
||||
|
||||
const readdirPromisified = promisify(readdir);
|
||||
const readFilePromisified = promisify(readFile);
|
||||
|
||||
const httpClient = new HttpClient();
|
||||
|
||||
/**
|
||||
* Check if something contains things
|
||||
*
|
||||
* @param thing Thing to check
|
||||
*/
|
||||
function doesContainThings<T extends SCThingWithoutReferences>(thing: T): boolean {
|
||||
/* tslint:disable-next-line:only-arrow-functions */
|
||||
return traverse(thing).reduce(function (sum, item) {
|
||||
if (this.isRoot) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return sum || (item === null) ? false : isThing(item);
|
||||
}, false);
|
||||
}
|
||||
|
||||
@suite()
|
||||
export class ConnectorClientSpec {
|
||||
async after() {
|
||||
sandbox.restore();
|
||||
}
|
||||
|
||||
@test
|
||||
async bulk() {
|
||||
sandbox.on(httpClient, 'request', async (): Promise<HttpClientResponse<SCBulkResponse>> => {
|
||||
return {
|
||||
body: {
|
||||
expiration: moment().add(1800, 'seconds').format(),
|
||||
source: 'foo',
|
||||
state: 'in progress',
|
||||
type: SCThingType.Message,
|
||||
uid: 'foo',
|
||||
},
|
||||
headers: {},
|
||||
statusCode: bulkRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.called();
|
||||
|
||||
const connectorClient = new ConnectorClient(httpClient, 'http://localhost');
|
||||
await connectorClient.bulk(SCThingType.Message, 'foo', 1800);
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: {
|
||||
expiration: moment().add(1800, 'seconds').format(),
|
||||
source: 'foo',
|
||||
type: SCThingType.Message,
|
||||
},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: bulkRoute.method,
|
||||
url: new URL('http://localhost' + bulkRoute.getUrlPath()),
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
async bulkWithoutTimeout() {
|
||||
sandbox.on(httpClient, 'request', async (): Promise<HttpClientResponse<SCBulkResponse>> => {
|
||||
return {
|
||||
body: {
|
||||
expiration: moment().add(3600, 'seconds').format(),
|
||||
source: 'foo',
|
||||
state: 'in progress',
|
||||
type: SCThingType.Message,
|
||||
uid: 'foo',
|
||||
},
|
||||
headers: {},
|
||||
statusCode: bulkRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.called();
|
||||
|
||||
const connectorClient = new ConnectorClient(httpClient, 'http://localhost');
|
||||
await connectorClient.bulk(SCThingType.Message, 'foo');
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: {
|
||||
expiration: moment().add(3600, 'seconds').format(),
|
||||
source: 'foo',
|
||||
type: SCThingType.Message,
|
||||
},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: bulkRoute.method,
|
||||
url: new URL('http://localhost' + bulkRoute.getUrlPath()),
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
async index() {
|
||||
const messages: SCMessage[] = [
|
||||
{
|
||||
audiences: [
|
||||
'employees',
|
||||
],
|
||||
categories: [
|
||||
'news'
|
||||
],
|
||||
messageBody: 'Lorem ipsum.',
|
||||
name: 'foo',
|
||||
origin: {
|
||||
indexed: 'foo',
|
||||
name: 'foo',
|
||||
type: SCThingOriginType.Remote,
|
||||
},
|
||||
type: SCThingType.Message,
|
||||
uid: 'foo',
|
||||
},
|
||||
{
|
||||
audiences: [
|
||||
'employees',
|
||||
],
|
||||
categories: [
|
||||
'news'
|
||||
],
|
||||
messageBody: 'Lorem ipsum.',
|
||||
name: 'foo',
|
||||
origin: {
|
||||
indexed: 'foo',
|
||||
name: 'foo',
|
||||
type: SCThingOriginType.Remote,
|
||||
},
|
||||
type: SCThingType.Message,
|
||||
uid: 'bar',
|
||||
},
|
||||
];
|
||||
|
||||
type responses = SCBulkResponse | SCBulkAddResponse | SCBulkDoneResponse;
|
||||
|
||||
sandbox.on(httpClient, 'request', async (request: HttpClientRequest)
|
||||
: Promise<HttpClientResponse<responses>> => {
|
||||
if (request.url.toString() === new URL('http://localhost' + bulkRoute.getUrlPath()).toString()) {
|
||||
return {
|
||||
body: {
|
||||
expiration: moment().add(3600, 'seconds').format(),
|
||||
source: 'copy',
|
||||
state: 'in progress',
|
||||
type: SCThingType.Message,
|
||||
uid: 'foo',
|
||||
},
|
||||
headers: {},
|
||||
statusCode: bulkRoute.statusCodeSuccess,
|
||||
};
|
||||
} else if (request.url.toString() === new URL('http://localhost' + bulkAddRoute.getUrlPath({
|
||||
UID: 'foo',
|
||||
})).toString()) {
|
||||
return {
|
||||
body: {},
|
||||
headers: {},
|
||||
statusCode: bulkAddRoute.statusCodeSuccess,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
body: {},
|
||||
headers: {},
|
||||
statusCode: bulkDoneRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
const connectorClient = new ConnectorClient(httpClient, 'http://localhost');
|
||||
await connectorClient.index(messages, 'copy');
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: {
|
||||
expiration: moment().add(3600, 'seconds').format(),
|
||||
source: 'copy',
|
||||
type: SCThingType.Message,
|
||||
},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: bulkRoute.method,
|
||||
url: new URL('http://localhost' + bulkRoute.getUrlPath()),
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
async indexFails() {
|
||||
const connectorClient = new ConnectorClient(httpClient, 'http://localhost');
|
||||
return connectorClient.index([]).should.be.rejectedWith(EmptyBulkError);
|
||||
}
|
||||
|
||||
@test
|
||||
async indexWithoutSource() {
|
||||
const messages: SCMessage[] = [
|
||||
{
|
||||
audiences: [
|
||||
'employees',
|
||||
],
|
||||
categories: [
|
||||
'news'
|
||||
],
|
||||
messageBody: 'Lorem ipsum.',
|
||||
name: 'foo',
|
||||
origin: {
|
||||
indexed: 'foo',
|
||||
name: 'foo',
|
||||
type: SCThingOriginType.Remote,
|
||||
},
|
||||
type: SCThingType.Message,
|
||||
uid: 'foo',
|
||||
},
|
||||
{
|
||||
audiences: [
|
||||
'employees',
|
||||
],
|
||||
categories: [
|
||||
'news'
|
||||
],
|
||||
messageBody: 'Lorem ipsum.',
|
||||
name: 'foo',
|
||||
origin: {
|
||||
indexed: 'foo',
|
||||
name: 'foo',
|
||||
type: SCThingOriginType.Remote,
|
||||
},
|
||||
type: SCThingType.Message,
|
||||
uid: 'bar',
|
||||
},
|
||||
];
|
||||
|
||||
type responses = SCBulkResponse | SCBulkAddResponse | SCBulkDoneResponse;
|
||||
|
||||
sandbox.on(httpClient, 'request', async (request: HttpClientRequest)
|
||||
: Promise<HttpClientResponse<responses>> => {
|
||||
if (request.url.toString() === new URL('http://localhost' + bulkRoute.getUrlPath()).toString()) {
|
||||
return {
|
||||
body: {
|
||||
expiration: moment().add(3600, 'seconds').format(),
|
||||
source: 'stapps-api',
|
||||
state: 'in progress',
|
||||
type: SCThingType.Message,
|
||||
uid: 'foo',
|
||||
},
|
||||
headers: {},
|
||||
statusCode: bulkRoute.statusCodeSuccess,
|
||||
};
|
||||
} else if (request.url.toString() === new URL('http://localhost' + bulkAddRoute.getUrlPath({
|
||||
UID: 'foo',
|
||||
})).toString()) {
|
||||
return {
|
||||
body: {},
|
||||
headers: {},
|
||||
statusCode: bulkAddRoute.statusCodeSuccess,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
body: {},
|
||||
headers: {},
|
||||
statusCode: bulkDoneRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
const connectorClient = new ConnectorClient(httpClient, 'http://localhost');
|
||||
await connectorClient.index(messages);
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: {
|
||||
expiration: moment().add(3600, 'seconds').format(),
|
||||
source: 'stapps-api',
|
||||
type: SCThingType.Message,
|
||||
},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: bulkRoute.method,
|
||||
url: new URL('http://localhost' + bulkRoute.getUrlPath()),
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
makeUuid() {
|
||||
const uuid = ConnectorClient.makeUUID('foo', 'b-tu');
|
||||
|
||||
expect(uuid).to.be.equal('abad271e-d9e9-5802-b7bc-96d8a647b451');
|
||||
expect(ConnectorClient.makeUUID('bar', 'b-tu')).not.to.be.equal(uuid);
|
||||
expect(ConnectorClient.makeUUID('foo', 'f-u')).not.to.be.equal(uuid);
|
||||
}
|
||||
|
||||
@test
|
||||
makeUuidFails() {
|
||||
expect(() => {
|
||||
ConnectorClient.makeUUID('foo', 'b-u');
|
||||
}).to.throw(NamespaceNotDefinedError);
|
||||
}
|
||||
|
||||
@test
|
||||
async removeReferences() {
|
||||
const pathToTestFiles = resolve(
|
||||
__dirname,
|
||||
'..',
|
||||
'node_modules',
|
||||
'@openstapps',
|
||||
'core',
|
||||
'test',
|
||||
'resources',
|
||||
'indexable'
|
||||
);
|
||||
|
||||
const testFiles = await readdirPromisified(pathToTestFiles);
|
||||
|
||||
const testInstances = await asyncPool(5, testFiles, async (testFile) => {
|
||||
const buffer = await readFilePromisified(join(pathToTestFiles, testFile));
|
||||
const content = JSON.parse(buffer.toString());
|
||||
|
||||
return content.instance;
|
||||
});
|
||||
|
||||
for (const testInstance of testInstances) {
|
||||
|
||||
const checkInstance = clone()(testInstance);
|
||||
const testInstanceWithoutReferences = ConnectorClient.removeReferences(testInstance);
|
||||
|
||||
expect(doesContainThings(testInstanceWithoutReferences)).to.be
|
||||
.equal(false, JSON.stringify(
|
||||
[testInstance, testInstanceWithoutReferences],
|
||||
null,
|
||||
2,
|
||||
));
|
||||
expect((testInstanceWithoutReferences as any).origin).to.be
|
||||
.equal(undefined, JSON.stringify(
|
||||
[testInstance, testInstanceWithoutReferences],
|
||||
null,
|
||||
2,
|
||||
));
|
||||
expect(testInstance).to.be.deep
|
||||
.equal(checkInstance,
|
||||
'Removing the references of a thing could have side effects because no deep copy is used');
|
||||
}
|
||||
}
|
||||
|
||||
@test
|
||||
async removeUndefinedProperties() {
|
||||
const objectWithUndefinedProperties = {value: 'foo',
|
||||
novalue: undefined,
|
||||
nested: {
|
||||
value: 'foo',
|
||||
novalue: undefined},
|
||||
};
|
||||
const objectWithoutUndefinedProperties = {value: 'foo',
|
||||
nested: {
|
||||
value: 'foo'},
|
||||
};
|
||||
ConnectorClient.removeUndefinedProperties(objectWithUndefinedProperties);
|
||||
|
||||
expect(objectWithUndefinedProperties).to.deep.equal(objectWithoutUndefinedProperties, JSON.stringify(
|
||||
[objectWithUndefinedProperties, objectWithoutUndefinedProperties],
|
||||
null,
|
||||
2,
|
||||
));
|
||||
}
|
||||
|
||||
@test
|
||||
async update() {
|
||||
const message: SCMessage = {
|
||||
audiences: [
|
||||
'employees',
|
||||
],
|
||||
categories: [
|
||||
'news'
|
||||
],
|
||||
messageBody: 'Lorem ipsum.',
|
||||
name: 'foo',
|
||||
origin: {
|
||||
indexed: 'foo',
|
||||
name: 'foo',
|
||||
type: SCThingOriginType.Remote,
|
||||
},
|
||||
type: SCThingType.Message,
|
||||
uid: 'foo',
|
||||
};
|
||||
|
||||
sandbox.on(httpClient, 'request', async (): Promise<HttpClientResponse<SCThingUpdateResponse>> => {
|
||||
return {
|
||||
body: {},
|
||||
headers: {},
|
||||
statusCode: thingUpdateRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.called();
|
||||
|
||||
const connectorClient = new ConnectorClient(httpClient, 'http://localhost');
|
||||
await connectorClient.update(message);
|
||||
|
||||
expect(httpClient.request).to.have.been.called.with({
|
||||
body: message,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: thingUpdateRoute.method,
|
||||
url: new URL('http://localhost' + thingUpdateRoute.getUrlPath({
|
||||
TYPE: SCThingType.Message,
|
||||
UID: 'foo',
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
198
packages/api/test/copy.spec.ts
Normal file
198
packages/api/test/copy.spec.ts
Normal file
@@ -0,0 +1,198 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {
|
||||
SCBulkAddResponse,
|
||||
SCBulkAddRoute,
|
||||
SCBulkDoneResponse,
|
||||
SCBulkDoneRoute,
|
||||
SCBulkResponse,
|
||||
SCBulkRoute,
|
||||
SCSearchRequest,
|
||||
SCSearchResponse,
|
||||
SCSearchRoute,
|
||||
SCThingType,
|
||||
} from '@openstapps/core';
|
||||
import chai from 'chai';
|
||||
import chaiAsPromised from 'chai-as-promised';
|
||||
import chaiSpies from 'chai-spies';
|
||||
import {suite, test} from '@testdeck/mocha';
|
||||
import moment from 'moment';
|
||||
import {copy} from '../src/copy';
|
||||
import {ApiError} from '../src/errors';
|
||||
import {HttpClient, RequestOptions, Response} from '../src/http-client';
|
||||
import {RecursivePartial} from './client.spec';
|
||||
|
||||
chai.should();
|
||||
chai.use(chaiSpies);
|
||||
chai.use(chaiAsPromised);
|
||||
|
||||
const sandbox = chai.spy.sandbox();
|
||||
|
||||
const bulkRoute = new SCBulkRoute();
|
||||
const bulkAddRoute = new SCBulkAddRoute();
|
||||
const bulkDoneRoute = new SCBulkDoneRoute();
|
||||
const searchRoute = new SCSearchRoute();
|
||||
|
||||
const httpClient = new HttpClient();
|
||||
|
||||
@suite()
|
||||
export class CopySpec {
|
||||
async after() {
|
||||
sandbox.restore();
|
||||
}
|
||||
|
||||
@test
|
||||
async copy() {
|
||||
type responses = Response<SCBulkAddResponse | SCBulkDoneResponse | SCBulkResponse | SCSearchResponse>;
|
||||
|
||||
sandbox.on(httpClient, 'request', async (request: RequestOptions): Promise<RecursivePartial<responses>> => {
|
||||
if (request.url.toString() === 'http://foo.bar' + searchRoute.getUrlPath().toString()) {
|
||||
const body = request.body as SCSearchRequest;
|
||||
|
||||
let count = 0;
|
||||
if (typeof body.size === 'number' && body.size > 0) {
|
||||
count = 1;
|
||||
}
|
||||
|
||||
return {
|
||||
body: {
|
||||
data: [{
|
||||
categories: [
|
||||
'main dish',
|
||||
],
|
||||
name: 'foobar',
|
||||
origin: {
|
||||
indexed: moment().format(),
|
||||
name: 'bar',
|
||||
},
|
||||
type: SCThingType.Dish,
|
||||
uid: 'foo',
|
||||
}],
|
||||
facets: [],
|
||||
pagination: {
|
||||
count: count,
|
||||
offset: 0,
|
||||
total: 1,
|
||||
},
|
||||
stats: {
|
||||
time: 1,
|
||||
},
|
||||
},
|
||||
statusCode: searchRoute.statusCodeSuccess,
|
||||
};
|
||||
} else if (request.url.toString() === 'http://localhost' + bulkRoute.getUrlPath().toString()) {
|
||||
return {
|
||||
body: {
|
||||
state: 'in progress',
|
||||
uid: 'foo',
|
||||
},
|
||||
statusCode: bulkRoute.statusCodeSuccess,
|
||||
};
|
||||
} else if (request.url.toString() === 'http://localhost' + bulkAddRoute.getUrlPath({
|
||||
UID: 'foo',
|
||||
}).toString()) {
|
||||
return {
|
||||
body: {},
|
||||
statusCode: bulkAddRoute.statusCodeSuccess,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
body: {},
|
||||
statusCode: bulkDoneRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
await copy(httpClient, {
|
||||
batchSize: 5,
|
||||
from: 'http://foo.bar',
|
||||
source: 'stapps-copy',
|
||||
to: 'http://localhost',
|
||||
type: SCThingType.Dish,
|
||||
version: 'foo.bar.foobar',
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
async copyShouldFail() {
|
||||
type responses = Response<SCBulkAddResponse | SCBulkDoneResponse | SCBulkResponse | SCSearchResponse>;
|
||||
|
||||
sandbox.on(httpClient, 'request', async (request: RequestOptions): Promise<RecursivePartial<responses>> => {
|
||||
if (request.url.toString() === 'http://foo.bar' + searchRoute.getUrlPath().toString()) {
|
||||
const body = request.body as SCSearchRequest;
|
||||
|
||||
if (typeof body.size === 'number' && body.size > 0) {
|
||||
throw new ApiError({});
|
||||
}
|
||||
|
||||
return {
|
||||
body: {
|
||||
data: [{
|
||||
categories: [
|
||||
'main dish',
|
||||
],
|
||||
name: 'foobar',
|
||||
origin: {
|
||||
indexed: moment().format(),
|
||||
name: 'bar',
|
||||
},
|
||||
type: SCThingType.Dish,
|
||||
uid: 'foo',
|
||||
}],
|
||||
facets: [],
|
||||
pagination: {
|
||||
count: 0,
|
||||
offset: 0,
|
||||
total: 1,
|
||||
},
|
||||
stats: {
|
||||
time: 1,
|
||||
},
|
||||
},
|
||||
statusCode: searchRoute.statusCodeSuccess,
|
||||
};
|
||||
} else if (request.url.toString() === 'http://localhost' + bulkRoute.getUrlPath().toString()) {
|
||||
return {
|
||||
body: {
|
||||
state: 'in progress',
|
||||
uid: 'foo',
|
||||
},
|
||||
statusCode: bulkRoute.statusCodeSuccess,
|
||||
};
|
||||
} else if (request.url.toString() === 'http://localhost' + bulkAddRoute.getUrlPath({
|
||||
UID: 'foo',
|
||||
}).toString()) {
|
||||
return {
|
||||
body: {},
|
||||
statusCode: bulkAddRoute.statusCodeSuccess,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
body: {},
|
||||
statusCode: bulkDoneRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
return copy(httpClient, {
|
||||
batchSize: 5,
|
||||
from: 'http://foo.bar',
|
||||
source: 'stapps-copy',
|
||||
to: 'http://localhost',
|
||||
type: SCThingType.Dish,
|
||||
version: 'foo.bar.foobar',
|
||||
}).should.be.rejectedWith(ApiError);
|
||||
}
|
||||
}
|
||||
200
packages/api/test/e2e.spec.ts
Normal file
200
packages/api/test/e2e.spec.ts
Normal file
@@ -0,0 +1,200 @@
|
||||
/*
|
||||
* Copyright (C) 2019 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// tslint:disable-next-line: max-line-length
|
||||
// tslint:disable: completed-docs no-implicit-dependencies prefer-function-over-method newline-per-chained-call member-ordering
|
||||
import {
|
||||
SCBulkAddResponse,
|
||||
SCBulkAddRoute,
|
||||
SCBulkDoneResponse,
|
||||
SCBulkDoneRoute,
|
||||
SCBulkResponse,
|
||||
SCBulkRoute,
|
||||
SCSearchResponse,
|
||||
SCSearchRoute,
|
||||
SCThings,
|
||||
} from '@openstapps/core';
|
||||
import chai from 'chai';
|
||||
import chaiAsPromised from 'chai-as-promised';
|
||||
import chaiSpies from 'chai-spies';
|
||||
import clone = require('rfdc');
|
||||
import {existsSync, mkdirSync, rmdirSync, unlinkSync} from 'fs';
|
||||
import {createFileSync} from 'fs-extra';
|
||||
import {suite, test} from '@testdeck/mocha';
|
||||
import {join} from 'path';
|
||||
import {e2eRun, getItemsFromSamples} from '../src/e2e';
|
||||
import {ApiError} from '../src/errors';
|
||||
import {HttpClient, RequestOptions, Response} from '../src/http-client';
|
||||
import {RecursivePartial} from './client.spec';
|
||||
|
||||
chai.should();
|
||||
chai.use(chaiSpies);
|
||||
chai.use(chaiAsPromised);
|
||||
|
||||
const sandbox = chai.spy.sandbox();
|
||||
|
||||
const bulkRoute = new SCBulkRoute();
|
||||
const bulkAddRoute = new SCBulkAddRoute();
|
||||
const bulkDoneRoute = new SCBulkDoneRoute();
|
||||
|
||||
const searchRoute = new SCSearchRoute();
|
||||
|
||||
const httpClient = new HttpClient();
|
||||
|
||||
const storedThings: Map<string, SCThings> = new Map();
|
||||
|
||||
@suite
|
||||
export class E2EConnectorSpec {
|
||||
async after() {
|
||||
sandbox.restore();
|
||||
}
|
||||
|
||||
@test
|
||||
async getCoreTestSamples() {
|
||||
const items = await getItemsFromSamples('./node_modules/@openstapps/core/test/resources');
|
||||
// tslint:disable-next-line: no-unused-expression
|
||||
chai.expect(items).to.not.be.empty;
|
||||
}
|
||||
|
||||
@test
|
||||
async getCoreTestSamplesShouldFail() {
|
||||
await chai.expect(getItemsFromSamples('./nonexistantdirectory')).to.be.rejectedWith(Error);
|
||||
}
|
||||
|
||||
@test
|
||||
async e2eRunSimulation() {
|
||||
type responses = Response<SCBulkAddResponse | SCBulkDoneResponse | SCBulkResponse | SCSearchResponse>;
|
||||
|
||||
let failOnCompare = false;
|
||||
let failOnLookup = false;
|
||||
|
||||
sandbox.on(httpClient, 'request', async (request: RequestOptions): Promise<RecursivePartial<responses>> => {
|
||||
if (request.url.toString() === `http://localhost${bulkRoute.getUrlPath().toString()}`) {
|
||||
|
||||
return {
|
||||
body: {
|
||||
state: 'in progress',
|
||||
uid: 'foo',
|
||||
},
|
||||
statusCode: bulkRoute.statusCodeSuccess,
|
||||
};
|
||||
}
|
||||
|
||||
if (request.url.toString() === `http://localhost${bulkAddRoute.getUrlPath({UID: 'foo'}).toString()}`) {
|
||||
storedThings.set(request.body.uid, clone()(request.body));
|
||||
|
||||
return {
|
||||
body: {},
|
||||
statusCode: bulkAddRoute.statusCodeSuccess,
|
||||
};
|
||||
}
|
||||
|
||||
if (request.url.toString() === `http://localhost${bulkDoneRoute.getUrlPath({UID: 'foo'}).toString()}`) {
|
||||
return {
|
||||
body: {},
|
||||
statusCode: bulkDoneRoute.statusCodeSuccess,
|
||||
};
|
||||
}
|
||||
|
||||
if (request.url.toString() === `http://localhost${searchRoute.getUrlPath().toString()}`) {
|
||||
const thing = storedThings.get(request.body.filter.arguments.value);
|
||||
if (failOnCompare) {
|
||||
thing!.origin!.modified = 'altered';
|
||||
}
|
||||
const returnThing = failOnLookup ? [] : [thing];
|
||||
const returnBody = {
|
||||
data: returnThing,
|
||||
facets: [],
|
||||
pagination: {
|
||||
count: returnThing.length,
|
||||
offset: 0,
|
||||
total: returnThing.length,
|
||||
},
|
||||
stats: {
|
||||
time: 42,
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
body: returnBody,
|
||||
statusCode: searchRoute.statusCodeSuccess,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
body: {},
|
||||
statusCode: searchRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
// tslint:disable-next-line: max-line-length
|
||||
await e2eRun(httpClient, {to: 'http://localhost', samplesLocation: './node_modules/@openstapps/core/test/resources'});
|
||||
|
||||
failOnLookup = true;
|
||||
failOnCompare = false;
|
||||
// tslint:disable-next-line: max-line-length
|
||||
await e2eRun(httpClient, {to: 'http://localhost', samplesLocation: './node_modules/@openstapps/core/test/resources'})
|
||||
.should.be.rejectedWith('Search for single SCThing with uid');
|
||||
|
||||
failOnLookup = false;
|
||||
failOnCompare = true;
|
||||
// tslint:disable-next-line: max-line-length
|
||||
await e2eRun(httpClient, {to: 'http://localhost', samplesLocation: './node_modules/@openstapps/core/test/resources'})
|
||||
.should.be.rejectedWith('Unexpected difference');
|
||||
|
||||
}
|
||||
|
||||
@test
|
||||
async indexShouldFail() {
|
||||
type responses = Response<SCBulkAddResponse | SCBulkDoneResponse | SCBulkResponse>;
|
||||
|
||||
sandbox.on(httpClient, 'request', async (): Promise<RecursivePartial<responses>> => {
|
||||
|
||||
return {
|
||||
body: {},
|
||||
statusCode: Number.MAX_SAFE_INTEGER,
|
||||
};
|
||||
});
|
||||
|
||||
// tslint:disable-next-line: max-line-length
|
||||
return e2eRun(httpClient, {to: 'http://localhost', samplesLocation: './node_modules/@openstapps/core/test/resources'})
|
||||
.should.be.rejectedWith(ApiError);
|
||||
}
|
||||
|
||||
@test
|
||||
async indexShouldFailDirectoryWithoutData() {
|
||||
const emptyDirPath = join(__dirname, 'emptyDir');
|
||||
if (!existsSync(emptyDirPath)) {
|
||||
mkdirSync(emptyDirPath);
|
||||
}
|
||||
await e2eRun(httpClient, {to: 'http://localhost', samplesLocation: emptyDirPath})
|
||||
.should.be.rejectedWith('Could not index samples. None were retrieved from the file system.');
|
||||
rmdirSync(emptyDirPath);
|
||||
}
|
||||
|
||||
@test
|
||||
async indexShouldFailDirectoryWithoutJsonData() {
|
||||
const somewhatFilledDirPath = join(__dirname, 'somewhatFilledDir');
|
||||
if (!existsSync(somewhatFilledDirPath)) {
|
||||
mkdirSync(somewhatFilledDirPath);
|
||||
}
|
||||
const nonJsonFile = join (somewhatFilledDirPath, 'nonjson.txt');
|
||||
createFileSync(nonJsonFile);
|
||||
await e2eRun(httpClient, {to: 'http://localhost', samplesLocation: somewhatFilledDirPath})
|
||||
.should.be.rejectedWith('Could not index samples. None were retrieved from the file system.');
|
||||
unlinkSync(nonJsonFile);
|
||||
rmdirSync(somewhatFilledDirPath);
|
||||
}
|
||||
}
|
||||
60
packages/api/test/errors.spec.ts
Normal file
60
packages/api/test/errors.spec.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import chai from 'chai';
|
||||
import {expect} from 'chai';
|
||||
import chaiAsPromised from 'chai-as-promised';
|
||||
import chaiSpies from 'chai-spies';
|
||||
import {suite, test} from '@testdeck/mocha';
|
||||
import {ApiError} from '../src/errors';
|
||||
|
||||
chai.should();
|
||||
chai.use(chaiSpies);
|
||||
chai.use(chaiAsPromised);
|
||||
|
||||
const sandbox = chai.spy.sandbox();
|
||||
|
||||
@suite()
|
||||
export class ErrorsSpec {
|
||||
async after() {
|
||||
sandbox.restore();
|
||||
}
|
||||
|
||||
@test
|
||||
async shouldAddAdditionalData() {
|
||||
const error = new ApiError({
|
||||
additionalData: 'Lorem ipsum',
|
||||
});
|
||||
|
||||
expect(error.toString()).to.contain('Lorem ipsum');
|
||||
}
|
||||
|
||||
@test
|
||||
async shouldAddRemoteStackTrace() {
|
||||
const error = new ApiError({
|
||||
stack: 'Lorem ipsum',
|
||||
});
|
||||
|
||||
expect(error.toString()).to.contain('Lorem ipsum');
|
||||
}
|
||||
|
||||
@test
|
||||
async shouldSetName() {
|
||||
const error = new ApiError({
|
||||
name: 'Foo',
|
||||
});
|
||||
|
||||
expect(error.name).to.be.equal('Foo');
|
||||
}
|
||||
}
|
||||
138
packages/api/test/http-client.spec.ts
Normal file
138
packages/api/test/http-client.spec.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
* Copyright (C) 2018-2020 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {expect} from 'chai';
|
||||
import {suite, test} from '@testdeck/mocha';
|
||||
import nock from 'nock';
|
||||
import {HttpClient} from '../src/http-client';
|
||||
|
||||
// TODO: use after each to clean up the nock (then there is no need for numerated resource links)
|
||||
|
||||
@suite()
|
||||
export class HttpClientSpec {
|
||||
|
||||
@test
|
||||
async construct() {
|
||||
expect(() => {
|
||||
return new HttpClient();
|
||||
}).not.to.throw();
|
||||
}
|
||||
|
||||
async after() {
|
||||
nock.cleanAll();
|
||||
}
|
||||
|
||||
@test
|
||||
async request() {
|
||||
const client = new HttpClient();
|
||||
|
||||
nock('http://www.example.com')
|
||||
.get('/resource')
|
||||
.reply(200, 'foo');
|
||||
|
||||
const response = await client.request({
|
||||
url: new URL('http://www.example.com/resource'),
|
||||
});
|
||||
|
||||
expect(response.body).to.be.equal('foo');
|
||||
}
|
||||
|
||||
@test
|
||||
async requestWithBody() {
|
||||
const client = new HttpClient();
|
||||
|
||||
nock('http://www.example.com')
|
||||
.get('/resource')
|
||||
.reply(200, 'foo');
|
||||
|
||||
const response = await client.request({
|
||||
url: new URL('http://www.example.com/resource')
|
||||
});
|
||||
|
||||
expect(response.body).to.be.equal('foo');
|
||||
}
|
||||
|
||||
@test
|
||||
async requestWithError() {
|
||||
const client = new HttpClient();
|
||||
let caughtErr;
|
||||
|
||||
nock('http://www.example.com')
|
||||
.get('/resource')
|
||||
.replyWithError('foo');
|
||||
|
||||
try {
|
||||
await client.request({
|
||||
body: {
|
||||
foo: 'bar',
|
||||
},
|
||||
url: new URL('http://www.example.com/resource'),
|
||||
});
|
||||
} catch (err) {
|
||||
caughtErr = err;
|
||||
}
|
||||
|
||||
expect(caughtErr).not.to.be.undefined;
|
||||
}
|
||||
|
||||
@test
|
||||
async requestWithHeaders() {
|
||||
const client = new HttpClient();
|
||||
|
||||
nock('http://www.example.com')
|
||||
.get('/resource')
|
||||
.reply(200, 'foo');
|
||||
|
||||
const response = await client.request({
|
||||
headers: {
|
||||
'X-StApps-Version': 'foo.bar.foobar',
|
||||
},
|
||||
url: new URL('http://www.example.com/resource'),
|
||||
});
|
||||
|
||||
expect(response.body).to.be.equal('foo');
|
||||
}
|
||||
|
||||
@test
|
||||
async requestWithMethodGet() {
|
||||
const client = new HttpClient();
|
||||
|
||||
nock('http://www.example.com')
|
||||
.get('/resource')
|
||||
.reply(200, 'foo');
|
||||
|
||||
const response = await client.request({
|
||||
method: 'GET',
|
||||
url: new URL('http://www.example.com/resource'),
|
||||
});
|
||||
|
||||
expect(response.body).to.be.equal('foo');
|
||||
}
|
||||
|
||||
@test
|
||||
async requestWithMethodPost() {
|
||||
const client = new HttpClient();
|
||||
|
||||
nock('http://www.example.com')
|
||||
.post('/resource')
|
||||
.reply(200, 'foo');
|
||||
|
||||
const response = await client.request({
|
||||
method: 'POST',
|
||||
url: new URL('http://www.example.com/resource'),
|
||||
});
|
||||
|
||||
expect(response.body).to.be.equal('foo');
|
||||
}
|
||||
}
|
||||
118
packages/api/test/plugin-client.spec.ts
Normal file
118
packages/api/test/plugin-client.spec.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* Copyright (C) 2019 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {SCPluginRegisterRequest, SCPluginRegisterResponse, SCPluginRegisterRoute} from '@openstapps/core';
|
||||
import chai from 'chai';
|
||||
import {expect} from 'chai';
|
||||
import chaiSpies from 'chai-spies';
|
||||
import {suite, test, timeout} from '@testdeck/mocha';
|
||||
import {HttpClient} from '../src/http-client';
|
||||
import {HttpClientResponse} from '../src/http-client-interface';
|
||||
import {PluginClient} from '../src/plugin-client';
|
||||
import {TestPlugin} from './plugin-resources/test-plugin';
|
||||
|
||||
chai.use(chaiSpies);
|
||||
|
||||
const sandbox = chai.spy.sandbox();
|
||||
|
||||
const httpClient = new HttpClient();
|
||||
|
||||
const pluginRegisterRoute = new SCPluginRegisterRoute();
|
||||
|
||||
const pluginClient = new PluginClient(httpClient, 'http://localhost');
|
||||
|
||||
@suite(timeout(10000))
|
||||
export class PluginClientSpec {
|
||||
static plugin: TestPlugin;
|
||||
|
||||
static async after() {
|
||||
await this.plugin.close();
|
||||
}
|
||||
|
||||
static async before() {
|
||||
this.plugin = new TestPlugin(4000, '', '', '', '', {getSchema: () => {/***/}} as any, '', '', '');
|
||||
}
|
||||
|
||||
async after() {
|
||||
sandbox.restore();
|
||||
}
|
||||
|
||||
@test
|
||||
async registerPlugin() {
|
||||
sandbox.on(httpClient, 'request', async (): Promise<HttpClientResponse<SCPluginRegisterResponse>> => {
|
||||
return {
|
||||
body: {
|
||||
success: true,
|
||||
},
|
||||
headers: {},
|
||||
statusCode: pluginRegisterRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.called();
|
||||
|
||||
await pluginClient.registerPlugin(PluginClientSpec.plugin);
|
||||
|
||||
const request: SCPluginRegisterRequest = {
|
||||
action: 'add',
|
||||
plugin: {
|
||||
address: PluginClientSpec.plugin.fullUrl,
|
||||
name: PluginClientSpec.plugin.name,
|
||||
requestSchema: PluginClientSpec.plugin.requestSchema,
|
||||
responseSchema: PluginClientSpec.plugin.responseSchema,
|
||||
route: PluginClientSpec.plugin.route,
|
||||
},
|
||||
};
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: request,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: pluginRegisterRoute.method,
|
||||
url: new URL(`http://localhost${pluginRegisterRoute.getUrlPath()}`),
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
async unregisterPlugin() {
|
||||
sandbox.on(httpClient, 'request', async (): Promise<HttpClientResponse<SCPluginRegisterResponse>> => {
|
||||
return {
|
||||
body: {
|
||||
success: true,
|
||||
},
|
||||
headers: {},
|
||||
statusCode: pluginRegisterRoute.statusCodeSuccess,
|
||||
};
|
||||
});
|
||||
|
||||
expect(httpClient.request).not.to.have.been.called();
|
||||
|
||||
await pluginClient.unregisterPlugin(PluginClientSpec.plugin);
|
||||
|
||||
const request: SCPluginRegisterRequest = {
|
||||
action: 'remove',
|
||||
route: PluginClientSpec.plugin.route,
|
||||
};
|
||||
|
||||
expect(httpClient.request).to.have.been.first.called.with({
|
||||
body: request,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: pluginRegisterRoute.method,
|
||||
url: new URL(`http://localhost${pluginRegisterRoute.getUrlPath()}`),
|
||||
});
|
||||
}
|
||||
}
|
||||
25
packages/api/test/plugin-resources/test-plugin-response.ts
Normal file
25
packages/api/test/plugin-resources/test-plugin-response.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright (C) 2021 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
/**
|
||||
* The Response Interface
|
||||
*
|
||||
* @validatable
|
||||
*/
|
||||
export interface TestPluginResponse {
|
||||
/**
|
||||
* Query dummy
|
||||
*/
|
||||
query: string;
|
||||
}
|
||||
32
packages/api/test/plugin-resources/test-plugin.ts
Normal file
32
packages/api/test/plugin-resources/test-plugin.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright (C) 2019 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import * as express from 'express';
|
||||
import {Plugin} from '../../src/plugin';
|
||||
|
||||
/**
|
||||
* A test plugin we use for all the tests
|
||||
*
|
||||
* It can be constructed without any parameter at all, or with all parameters if we want to test it
|
||||
* It also serves as kind of a minimal plugin
|
||||
*/
|
||||
export class TestPlugin extends Plugin {
|
||||
// tslint:disable-next-line: completed-docs prefer-function-over-method
|
||||
protected async onRouteInvoke(_req: express.Request, res: express.Response): Promise<void> {
|
||||
res.json({});
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
141
packages/api/test/plugin.spec.ts
Normal file
141
packages/api/test/plugin.spec.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
/*
|
||||
* Copyright (C) 2019 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {Converter} from '@openstapps/core-tools/lib/schema';
|
||||
import chai from 'chai';
|
||||
import {expect} from 'chai';
|
||||
import chaiSpies from 'chai-spies';
|
||||
import {readFileSync} from 'fs';
|
||||
import {suite, test, timeout} from '@testdeck/mocha';
|
||||
import {resolve} from 'path';
|
||||
import {HttpClient} from '../src/http-client';
|
||||
import {TestPlugin} from './plugin-resources/test-plugin';
|
||||
|
||||
chai.use(chaiSpies);
|
||||
|
||||
process.on('unhandledRejection', (err) => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
const sandbox = chai.spy.sandbox();
|
||||
|
||||
const httpClient = new HttpClient();
|
||||
|
||||
@suite(timeout(20000))
|
||||
export class PluginSpec {
|
||||
static testPlugin: TestPlugin;
|
||||
|
||||
static async after() {
|
||||
PluginSpec.testPlugin.close();
|
||||
}
|
||||
|
||||
static async before() {
|
||||
PluginSpec.testPlugin = new TestPlugin(4000, '', '', '', '', {
|
||||
getSchema: () => {/***/
|
||||
},
|
||||
} as any, '', '', '');
|
||||
}
|
||||
|
||||
async after() {
|
||||
sandbox.restore();
|
||||
}
|
||||
|
||||
@test
|
||||
async construct() {
|
||||
const converter = new Converter(__dirname, resolve(__dirname,'plugin-resources','test-plugin-response.ts'));
|
||||
|
||||
sandbox.on(converter, 'getSchema', (schemaName) => {
|
||||
return {$id: schemaName};
|
||||
});
|
||||
|
||||
const constructTestPlugin = new TestPlugin(
|
||||
4001,
|
||||
'A',
|
||||
'http://B',
|
||||
'/C', // this doesn't matter for our tests, it's only something that affects the backend
|
||||
'http://D',
|
||||
// @ts-ignore fake converter is not a converter
|
||||
converter,
|
||||
'PluginTestRequest',
|
||||
'PluginTestResponse',
|
||||
JSON.parse(readFileSync(resolve(__dirname, '..', 'package.json')).toString()).version,
|
||||
);
|
||||
expect(constructTestPlugin.port).to.be.equal(4001);
|
||||
expect(constructTestPlugin.name).to.be.equal('A');
|
||||
expect(constructTestPlugin.url).to.be.equal('http://B');
|
||||
expect(constructTestPlugin.route).to.be.equal('/C');
|
||||
// @ts-ignore backendUrl is protected
|
||||
expect(constructTestPlugin.backendUrl).to.be.equal('http://D');
|
||||
// schemas are already covered, together with the directory and version
|
||||
// @ts-ignore active is private
|
||||
expect(constructTestPlugin.active).to.be.equal(false);
|
||||
expect(constructTestPlugin.requestSchema.$id).to.be.equal('PluginTestRequest');
|
||||
expect(constructTestPlugin.responseSchema.$id).to.be.equal('PluginTestResponse');
|
||||
|
||||
sandbox.on(constructTestPlugin, 'onRouteInvoke');
|
||||
await httpClient.request({
|
||||
url: new URL('http://localhost:4001'),
|
||||
});
|
||||
// onRouteInvoke is a protected method, but we need to access it from the outside to test it
|
||||
// @ts-ignore
|
||||
expect(constructTestPlugin.onRouteInvoke).not.to.have.been.called();
|
||||
|
||||
await constructTestPlugin.close();
|
||||
sandbox.restore(constructTestPlugin, 'onRouteInvoke');
|
||||
}
|
||||
|
||||
@test
|
||||
async fullUrl() {
|
||||
const constructTestPlugin = new TestPlugin(4001, '', 'http://B', '', '', {
|
||||
getSchema: () => {/***/
|
||||
},
|
||||
} as any, '', '', '');
|
||||
expect(constructTestPlugin.fullUrl).to.be.equal('http://B:4001');
|
||||
await constructTestPlugin.close();
|
||||
}
|
||||
|
||||
@test
|
||||
async start() {
|
||||
PluginSpec.testPlugin.start();
|
||||
|
||||
sandbox.on(PluginSpec.testPlugin, 'onRouteInvoke');
|
||||
|
||||
await httpClient.request({
|
||||
url: new URL('http://localhost:4000'),
|
||||
});
|
||||
|
||||
// onRouteInvoke is a protected method, but we need to access it from the outside to test it
|
||||
// @ts-ignore
|
||||
expect(PluginSpec.testPlugin.onRouteInvoke).to.have.been.called();
|
||||
}
|
||||
|
||||
@test
|
||||
async stop() {
|
||||
// simulate a normal use case by first starting the plugin and then stopping it
|
||||
PluginSpec.testPlugin.start();
|
||||
PluginSpec.testPlugin.stop();
|
||||
|
||||
sandbox.on(PluginSpec.testPlugin, 'onRouteInvoke');
|
||||
|
||||
const response = await httpClient.request({
|
||||
url: new URL('http://localhost:4000'),
|
||||
});
|
||||
|
||||
await expect(response.statusCode).to.be.equal(404);
|
||||
// onRouteInvoke is a protected method, but we need to access it from the outside to test it
|
||||
// @ts-ignore
|
||||
expect(PluginSpec.testPlugin.onRouteInvoke).not.to.have.been.called();
|
||||
}
|
||||
}
|
||||
3
packages/api/tsconfig.json
Normal file
3
packages/api/tsconfig.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "./node_modules/@openstapps/configuration/tsconfig.json"
|
||||
}
|
||||
Reference in New Issue
Block a user