Compare commits

...
Author SHA1 Message Date
William Schurman 6222f0f464 feat: dataloaders within transactions 2020-12-10 15:34:56 -08:00
Will Schurman e3b2b235f8 v0.10.0 (#97) 2020-11-16 20:27:33 -08:00
Will Schurman d9603298e0 fix: fix null handling in load paths (try 2) (#96) 2020-11-16 20:03:32 -08:00
Will Schurman b22c734275 v0.9.1 (#94) 2020-11-06 09:11:55 -08:00
Will Schurman 012c05d62d fix: edge deletion behavior cyclic import structure again (#93) 2020-11-06 08:52:37 -08:00
Will Schurman ead9561cc7 v0.9.0 (#92) 2020-11-05 14:40:17 -08:00
Will Schurman d1a6f13396 feat: add ability to invalidate an entity manually (#91) 2020-11-05 12:38:14 -08:00
Will Schurman cca8fc1987 fix: edge deletion behavior cyclic import structure (#89) 2020-11-05 10:08:50 -08:00
Will Schurman 86aa5b291d v0.8.1 (#87) 2020-10-09 12:07:19 -07:00
Will Schurman 4026fc1a61 docs: update to add 2FA token note to release process 2020-10-09 10:59:58 -07:00
Will Schurman a263e74b8a fix!: add entity name to loader counter metric events (#86) 2020-10-09 10:48:00 -07:00
Will Schurman f737fa5b28 v0.8.0 (#85) 2020-10-09 10:11:22 -07:00
Will Schurman 884320ac53 docs: update readme one last time for release process 2020-10-09 10:06:34 -07:00
Will Schurman 40906202cf docs: update readme again for release process 2020-10-09 10:04:30 -07:00
Will Schurman 6cdd720c98 docs: update readme for release process (#84) 2020-10-09 09:58:16 -07:00
Will Schurman f4cdc01c6c feat: add entityClassName to metrics adapter events (#83) 2020-10-08 14:47:20 -07:00
Will Schurman d0cd8d88f2 v0.7.1 (#82) 2020-09-30 20:31:20 -07:00
Will Schurman f98f7d14b6 fix: correct type of runInTransactionAsync (#81) 2020-09-30 20:19:40 -07:00
Will Schurman f4b30cb704 v0.7.0 (#80) 2020-09-30 19:55:22 -07:00
Will Schurman 22aa907b11 docs: fix typedoc (#79) 2020-08-25 14:05:28 -07:00
Will Schurman 9891e74694 fix: upgrade packages (#78) 2020-08-25 13:38:00 -07:00
Will Schurman dbc3c81b35 fix: move cache invalidation to after transaction commit (#77) 2020-08-25 11:16:16 -07:00
Will Schurman 62bfd6c703 fix!: constuctor thrown exceptions for loadMany (#74) 2020-07-29 10:35:28 -07:00
Will Schurman 7e829f30fd fix: fix index export for EntityMutationTrigger and EntityMutationValidator (#73) 2020-07-28 15:09:45 -07:00
Will Schurman cd2df8da4b fix: fix incorrect loader types for field selecitons (#72) 2020-07-28 15:01:33 -07:00
Will Schurman b580a218c0 v0.6.0 (#69) 2020-07-23 14:48:27 -07:00
Will Schurman 547a1efcec fix: separate out EntityMutationValidator (#68) 2020-07-23 14:22:02 -07:00
Quinlan Jung fc4377d883 feat: entity mutation validators (#67)
* entity mutation validators

* pr feedback

* tests
2020-07-23 11:03:20 -07:00
Will Schurman 5744c51e6b fix: ensure transitive deletion triggers are run for CASCADE_DELETE_INVALIDATE_CACHE (#66) 2020-07-22 19:26:32 -07:00
Will Schurman fd6060cc84 feat: mutation triggers (#65) 2020-07-22 16:57:46 -07:00
Will Schurman a757867360 fix!: remove lodash dependency for vuln, require node 12 (#64) 2020-07-22 10:48:12 -07:00
Will Schurman 1224de79d5 feat!: add support for reference deletion and enclose mutations in transactions (#63) 2020-07-22 09:47:37 -07:00
Will Schurman 7a77afc83e fix: update setField to correct typing (#62) 2020-07-10 17:00:13 -07:00
Will Schurman 9c92d10b80 v0.5.2 (#60) 2020-07-01 22:04:27 -07:00
Will Schurman 7c180e84d9 fix: fix stub cache key generation for global cache (#59) 2020-07-01 22:00:55 -07:00
81 changed files with 7002 additions and 1951 deletions

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 10.x
node-version: 12.x
- name: Cache Node.js modules
uses: actions/cache@v1
with:
+1 -1
View File
@@ -14,7 +14,7 @@ jobs:
ref: ${{ github.event.pull_request.head.sha }}
- uses: actions/setup-node@v1
with:
node-version: 10.x
node-version: 12.x
- name: Cache Node.js modules
uses: actions/cache@v1
with:
+112
View File
@@ -3,6 +3,118 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [0.10.0](https://github.com/expo/entity/compare/v0.9.1...v0.10.0) (2020-11-17)
### Bug Fixes
* fix null handling in load paths (try 2) ([#96](https://github.com/expo/entity/issues/96)) ([d960329](https://github.com/expo/entity/commit/d9603298e0cc5c3c2b0cca959876e9195555fb57))
## [0.9.1](https://github.com/expo/entity/compare/v0.9.0...v0.9.1) (2020-11-06)
### Bug Fixes
* edge deletion behavior cyclic import structure again ([#93](https://github.com/expo/entity/issues/93)) ([012c05d](https://github.com/expo/entity/commit/012c05d62d2ecd559eb331c6ca358052bfe66dc8))
# [0.9.0](https://github.com/expo/entity/compare/v0.8.1...v0.9.0) (2020-11-05)
### Bug Fixes
* edge deletion behavior cyclic import structure ([#89](https://github.com/expo/entity/issues/89)) ([cca8fc1](https://github.com/expo/entity/commit/cca8fc19870057ebc7033081b59fab4a142fbf1a))
### Features
* add ability to invalidate an entity manually ([#91](https://github.com/expo/entity/issues/91)) ([d1a6f13](https://github.com/expo/entity/commit/d1a6f1339648942f12b3fb605eb329aefe5cdd63))
## [0.8.1](https://github.com/expo/entity/compare/v0.8.0...v0.8.1) (2020-10-09)
**Note:** Version bump only for package root
# [0.8.0](https://github.com/expo/entity/compare/v0.7.1...v0.8.0) (2020-10-09)
### Features
* add entityClassName to metrics adapter events ([#83](https://github.com/expo/entity/issues/83)) ([f4cdc01](https://github.com/expo/entity/commit/f4cdc01c6cb8868c24ce3da2274f0901687e05bd))
## [0.7.1](https://github.com/expo/entity/compare/v0.7.0...v0.7.1) (2020-10-01)
### Bug Fixes
* correct type of runInTransactionAsync ([#81](https://github.com/expo/entity/issues/81)) ([f98f7d1](https://github.com/expo/entity/commit/f98f7d14b6149a496a7a3e97dd63d89b2842cc26))
# [0.7.0](https://github.com/expo/entity/compare/v0.6.0...v0.7.0) (2020-10-01)
### Bug Fixes
* fix incorrect loader types for field selecitons ([#72](https://github.com/expo/entity/issues/72)) ([cd2df8d](https://github.com/expo/entity/commit/cd2df8da4b81bcd4769e950d3124c18886df2816))
* fix index export for EntityMutationTrigger and EntityMutationValidator ([#73](https://github.com/expo/entity/issues/73)) ([7e829f3](https://github.com/expo/entity/commit/7e829f30fde0bd343cb8a584ccda5530cf61ec33))
* move cache invalidation to after transaction commit ([#77](https://github.com/expo/entity/issues/77)) ([dbc3c81](https://github.com/expo/entity/commit/dbc3c81b359a668b5134189ce6de49b5893bb5e7))
* upgrade packages ([#78](https://github.com/expo/entity/issues/78)) ([9891e74](https://github.com/expo/entity/commit/9891e7469467a28589f529c8d87b10fc2232d3ff))
# [0.6.0](https://github.com/expo/entity/compare/v0.5.2...v0.6.0) (2020-07-23)
### Bug Fixes
* ensure transitive deletion triggers are run for CASCADE_DELETE_INVALIDATE_CACHE ([#66](https://github.com/expo/entity/issues/66)) ([5744c51](https://github.com/expo/entity/commit/5744c51e6b3178bd9f229f3f465b683bb4474c8a))
* separate out EntityMutationValidator ([#68](https://github.com/expo/entity/issues/68)) ([547a1ef](https://github.com/expo/entity/commit/547a1efcecd17cc085702d1a3e9888ce5b644b13))
* update setField to correct typing ([#62](https://github.com/expo/entity/issues/62)) ([7a77afc](https://github.com/expo/entity/commit/7a77afc83ea732c9b062a5d6865eff9d3131d015))
### Features
* entity mutation validators ([#67](https://github.com/expo/entity/issues/67)) ([fc4377d](https://github.com/expo/entity/commit/fc4377d8839da07417b88afc138f73556383d896))
* mutation triggers ([#65](https://github.com/expo/entity/issues/65)) ([fd6060c](https://github.com/expo/entity/commit/fd6060cc844f60635b3ce4c400c4877f2df8fa44))
## [0.5.2](https://github.com/expo/entity/compare/v0.5.1...v0.5.2) (2020-07-02)
### Bug Fixes
* fix stub cache key generation for global cache ([#59](https://github.com/expo/entity/issues/59)) ([7c180e8](https://github.com/expo/entity/commit/7c180e84d9a8cdfd9380fac0eab2d02a96ec18f3))
## [0.5.1](https://github.com/expo/entity/compare/v0.5.0...v0.5.1) (2020-07-01)
+15
View File
@@ -78,6 +78,21 @@ Entity is not limited in where it can or should be used, but was designed for us
Note: The entity framework instance should not be shared across multiple requests since it contains a unique memoized [Dataloader](https://github.com/graphql/dataloader#class-dataloader). A long-lived instance is prone to data synchronization issues, especially when the application is scaled horizontally and multiple shared caches would exist for the same data.
## Releasing
To release a new version, let's say `v1.0.0` for example:
1. `git checkout -b bump-v1.0.0`
1. `yarn lerna version minor -- --no-push --conventional-commits`
1. `git push -u origin bump-v1.0.0`
1. Create a PR from the `bump-v1.0.0` branch, wait for tests, and commit the PR using GitHub interface.
1. `git checkout master && git pull`
1. `git tag -d v1.0.0`
1. `git tag v1.0.0`
1. `git push origin v1.0.0`
1. In GitHub release interface, create a new release from the tag, copy changelog changes to release description.
1. `yarn clean && yarn tsc`
1. In each public subpackage, run `npm publish` and enter 2FA token.
## License
The Entity source code is made available under the [MIT license](LICENSE).
+1 -1
View File
@@ -4,5 +4,5 @@
],
"npmClient": "yarn",
"useWorkspaces": true,
"version": "0.5.1"
"version": "0.10.0"
}
+19 -20
View File
@@ -14,29 +14,28 @@
},
"devDependencies": {
"@expo/entity": "file:packages/entity",
"@expo/results": "^0.3.0",
"@types/invariant": "^2.2.32",
"@types/ioredis": "^4.14.9",
"@types/jest": "^25.2.1",
"@types/lodash": "^4.14.150",
"@types/node": "^13.13.4",
"@types/uuid": "^7.0.3",
"@typescript-eslint/eslint-plugin": "^2.30.0",
"@typescript-eslint/parser": "^2.30.0",
"@expo/results": "^1.0.0",
"@types/invariant": "^2.2.33",
"@types/ioredis": "^4.17.3",
"@types/jest": "^26.0.10",
"@types/node": "^14.6.0",
"@types/uuid": "^8.3.0",
"@typescript-eslint/eslint-plugin": "^3.10.1",
"@typescript-eslint/parser": "^3.10.1",
"barrelsby": "^2.2.0",
"eslint": "^6.8.0",
"eslint-config-universe": "^3.0.0",
"eslint-plugin-tsdoc": "^0.2.4",
"jest": "^24.9.0",
"lerna": "^3.20.2",
"pg": "^8.0.3",
"prettier": "^2.0.5",
"ts-jest": "~24.2.0",
"ts-mockito": "^2.5.0",
"eslint": "^7.7.0",
"eslint-config-universe": "^4.0.0",
"eslint-plugin-tsdoc": "^0.2.6",
"jest": "^26.4.2",
"lerna": "^3.22.1",
"pg": "^8.3.2",
"prettier": "^2.1.0",
"ts-jest": "~26.2.0",
"ts-mockito": "^2.6.1",
"typedoc": "^0.17.6",
"typedoc-plugin-lerna-packages": "^0.3.0",
"typescript": "^3.9.2",
"uuid": "^7.0.3"
"typescript": "^4.0.2",
"uuid": "^8.3.0"
},
"dependencies": {
"@expo/entity": "file:packages/entity",
@@ -3,6 +3,81 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [0.10.0](https://github.com/expo/entity/compare/v0.9.1...v0.10.0) (2020-11-17)
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
## [0.9.1](https://github.com/expo/entity/compare/v0.9.0...v0.9.1) (2020-11-06)
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
# [0.9.0](https://github.com/expo/entity/compare/v0.8.1...v0.9.0) (2020-11-05)
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
## [0.8.1](https://github.com/expo/entity/compare/v0.8.0...v0.8.1) (2020-10-09)
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
# [0.8.0](https://github.com/expo/entity/compare/v0.7.1...v0.8.0) (2020-10-09)
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
## [0.7.1](https://github.com/expo/entity/compare/v0.7.0...v0.7.1) (2020-10-01)
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
# [0.7.0](https://github.com/expo/entity/compare/v0.6.0...v0.7.0) (2020-10-01)
### Bug Fixes
* upgrade packages ([#78](https://github.com/expo/entity/issues/78)) ([9891e74](https://github.com/expo/entity/commit/9891e7469467a28589f529c8d87b10fc2232d3ff))
# [0.6.0](https://github.com/expo/entity/compare/v0.5.2...v0.6.0) (2020-07-23)
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
## [0.5.2](https://github.com/expo/entity/compare/v0.5.1...v0.5.2) (2020-07-02)
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
## [0.5.1](https://github.com/expo/entity/compare/v0.5.0...v0.5.1) (2020-07-01)
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
@@ -1,6 +1,6 @@
{
"name": "@expo/entity-cache-adapter-redis",
"version": "0.5.1",
"version": "0.10.0",
"description": "Redis cache adapter for @expo/entity",
"files": [
"build",
@@ -12,13 +12,13 @@
"tsc": "tsc",
"clean": "rm -rf build coverage coverage-integration",
"lint": "eslint src --ext '.ts'",
"test": "jest --rootDir --config ../../resources/jest.config.js",
"test": "jest --rootDir . --config ../../resources/jest.config.js",
"integration": "../../resources/run-with-docker yarn integration-no-setup",
"integration-no-setup": "jest --config ../../resources/jest-integration.config.js --rootDir --runInBand --passWithNoTests",
"integration-no-setup": "jest --config ../../resources/jest-integration.config.js --rootDir . --runInBand --passWithNoTests",
"barrelsby": "barrelsby --directory src --location top --exclude tests__ --singleQuotes --exportDefault --delete"
},
"engines": {
"node": ">=8"
"node": ">=12"
},
"keywords": [
"entity"
@@ -29,9 +29,9 @@
"@expo/entity": "*"
},
"dependencies": {
"ioredis": "^4.16.1"
"ioredis": "^4.17.3"
},
"devDependencies": {
"@expo/entity": "^0.5.1"
"@expo/entity": "^0.10.0"
}
}
@@ -47,10 +47,14 @@ describe(RedisCacheAdapter, () => {
)['tableDataCoordinator']['cacheAdapter'];
const cacheKeyMaker = cacheAdapter['makeCacheKey'].bind(cacheAdapter);
// creating an entity should put it in cache (loader loads it after creation)
const entity1 = await enforceAsyncResult(
RedisTestEntity.creator(vc1).setField('name', 'blah').createAsync()
);
const entity1Created = await RedisTestEntity.creator(vc1)
.setField('name', 'blah')
.enforceCreateAsync();
// loading an entity should put it in cache
const entity1 = await RedisTestEntity.loader(vc1)
.enforcing()
.loadByIDAsync(entity1Created.getID());
const cachedJSON = await redisCacheAdapterContext.redisClient.get(
cacheKeyMaker('id', entity1.getID())
@@ -3,6 +3,92 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [0.10.0](https://github.com/expo/entity/compare/v0.9.1...v0.10.0) (2020-11-17)
**Note:** Version bump only for package @expo/entity-database-adapter-knex
## [0.9.1](https://github.com/expo/entity/compare/v0.9.0...v0.9.1) (2020-11-06)
**Note:** Version bump only for package @expo/entity-database-adapter-knex
# [0.9.0](https://github.com/expo/entity/compare/v0.8.1...v0.9.0) (2020-11-05)
**Note:** Version bump only for package @expo/entity-database-adapter-knex
## [0.8.1](https://github.com/expo/entity/compare/v0.8.0...v0.8.1) (2020-10-09)
**Note:** Version bump only for package @expo/entity-database-adapter-knex
# [0.8.0](https://github.com/expo/entity/compare/v0.7.1...v0.8.0) (2020-10-09)
**Note:** Version bump only for package @expo/entity-database-adapter-knex
## [0.7.1](https://github.com/expo/entity/compare/v0.7.0...v0.7.1) (2020-10-01)
**Note:** Version bump only for package @expo/entity-database-adapter-knex
# [0.7.0](https://github.com/expo/entity/compare/v0.6.0...v0.7.0) (2020-10-01)
### Bug Fixes
* fix index export for EntityMutationTrigger and EntityMutationValidator ([#73](https://github.com/expo/entity/issues/73)) ([7e829f3](https://github.com/expo/entity/commit/7e829f30fde0bd343cb8a584ccda5530cf61ec33))
* move cache invalidation to after transaction commit ([#77](https://github.com/expo/entity/issues/77)) ([dbc3c81](https://github.com/expo/entity/commit/dbc3c81b359a668b5134189ce6de49b5893bb5e7))
* upgrade packages ([#78](https://github.com/expo/entity/issues/78)) ([9891e74](https://github.com/expo/entity/commit/9891e7469467a28589f529c8d87b10fc2232d3ff))
# [0.6.0](https://github.com/expo/entity/compare/v0.5.2...v0.6.0) (2020-07-23)
### Bug Fixes
* separate out EntityMutationValidator ([#68](https://github.com/expo/entity/issues/68)) ([547a1ef](https://github.com/expo/entity/commit/547a1efcecd17cc085702d1a3e9888ce5b644b13))
### Features
* entity mutation validators ([#67](https://github.com/expo/entity/issues/67)) ([fc4377d](https://github.com/expo/entity/commit/fc4377d8839da07417b88afc138f73556383d896))
* mutation triggers ([#65](https://github.com/expo/entity/issues/65)) ([fd6060c](https://github.com/expo/entity/commit/fd6060cc844f60635b3ce4c400c4877f2df8fa44))
## [0.5.2](https://github.com/expo/entity/compare/v0.5.1...v0.5.2) (2020-07-02)
**Note:** Version bump only for package @expo/entity-database-adapter-knex
## [0.5.1](https://github.com/expo/entity/compare/v0.5.0...v0.5.1) (2020-07-01)
@@ -1,6 +1,6 @@
{
"name": "@expo/entity-database-adapter-knex",
"version": "0.5.1",
"version": "0.10.0",
"description": "Knex database adapter for @expo/entity",
"files": [
"build",
@@ -12,13 +12,13 @@
"tsc": "tsc",
"clean": "rm -rf build coverage coverage-integration",
"lint": "eslint src --ext '.ts'",
"test": "jest --rootDir --config ../../resources/jest.config.js --passWithNoTests",
"test": "jest --rootDir . --config ../../resources/jest.config.js --passWithNoTests",
"integration": "../../resources/run-with-docker yarn integration-no-setup",
"integration-no-setup": "jest --config ../../resources/jest-integration.config.js --rootDir --runInBand --passWithNoTests",
"integration-no-setup": "jest --config ../../resources/jest-integration.config.js --rootDir . --runInBand --passWithNoTests",
"barrelsby": "barrelsby --directory src --location top --exclude tests__ --singleQuotes --exportDefault --delete"
},
"engines": {
"node": ">=8"
"node": ">=12"
},
"keywords": [
"entity"
@@ -29,9 +29,9 @@
"@expo/entity": "*"
},
"dependencies": {
"knex": "^0.20.11"
"knex": "^0.21.5"
},
"devDependencies": {
"@expo/entity": "^0.5.1"
"@expo/entity": "^0.10.0"
}
}
@@ -1,25 +1,21 @@
import {
IEntityQueryContextProvider,
EntityNonTransactionalQueryContext,
EntityTransactionalQueryContext,
} from '@expo/entity';
import { EntityQueryContextProvider } from '@expo/entity';
import Knex from 'knex';
/**
* Query context provider for knex (postgres).
*/
export default class PostgresEntityQueryContextProvider implements IEntityQueryContextProvider {
constructor(private readonly knexInstance: Knex) {}
getRegularEntityQueryContext(): EntityNonTransactionalQueryContext {
return new EntityNonTransactionalQueryContext(this.knexInstance);
export default class PostgresEntityQueryContextProvider extends EntityQueryContextProvider {
constructor(private readonly knexInstance: Knex) {
super();
}
async runInTransactionAsync<T>(
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>
): Promise<T> {
return await this.knexInstance.transaction(async (trx) => {
return await transactionScope(new EntityTransactionalQueryContext(trx));
});
protected getQueryInterface(): any {
return this.knexInstance;
}
protected createTransactionRunner<T>(): (
transactionScope: (trx: any) => Promise<T>
) => Promise<T> {
return (transactionScope) => this.knexInstance.transaction(transactionScope);
}
}
@@ -8,6 +8,8 @@ import { enforceAsyncResult } from '@expo/results';
import Knex from 'knex';
import PostgresTestEntity from '../testfixtures/PostgresTestEntity';
import PostgresTriggerTestEntity from '../testfixtures/PostgresTriggerTestEntity';
import PostgresValidatorTestEntity from '../testfixtures/PostgresValidatorTestEntity';
import { createKnexIntegrationTestEntityCompanionProvider } from '../testfixtures/createKnexIntegrationTestEntityCompanionProvider';
describe('postgres entity integration', () => {
@@ -32,7 +34,7 @@ describe('postgres entity integration', () => {
afterAll(async () => {
await PostgresTestEntity.dropPostgresTable(knexInstance);
knexInstance.destroy();
await knexInstance.destroy();
});
it('supports parallel partial updates', async () => {
@@ -325,4 +327,223 @@ describe('postgres entity integration', () => {
expect(resultsMultipleOrderBy.map((e) => e.getField('name'))).toEqual(['c', 'b', 'a']);
});
});
describe('trigger transaction behavior', () => {
describe('create', () => {
it('rolls back transaction when trigger throws except afterCommit', async () => {
const vc1 = new ViewerContext(
createKnexIntegrationTestEntityCompanionProvider(knexInstance)
);
await expect(
PostgresTriggerTestEntity.creator(vc1)
.setField('name', 'beforeCreate')
.enforceCreateAsync()
).rejects.toThrowError('name cannot have value beforeCreate');
await expect(
PostgresTriggerTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'beforeCreate')
).resolves.toBeNull();
await expect(
PostgresTriggerTestEntity.creator(vc1)
.setField('name', 'afterCreate')
.enforceCreateAsync()
).rejects.toThrowError('name cannot have value afterCreate');
await expect(
PostgresTriggerTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'afterCreate')
).resolves.toBeNull();
await expect(
PostgresTriggerTestEntity.creator(vc1).setField('name', 'beforeAll').enforceCreateAsync()
).rejects.toThrowError('name cannot have value beforeAll');
await expect(
PostgresTriggerTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'beforeAll')
).resolves.toBeNull();
await expect(
PostgresTriggerTestEntity.creator(vc1).setField('name', 'afterAll').enforceCreateAsync()
).rejects.toThrowError('name cannot have value afterAll');
await expect(
PostgresTriggerTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'afterAll')
).resolves.toBeNull();
await expect(
PostgresTriggerTestEntity.creator(vc1)
.setField('name', 'afterCommit')
.enforceCreateAsync()
).rejects.toThrowError('name cannot have value afterCommit');
await expect(
PostgresTriggerTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'afterCommit')
).resolves.not.toBeNull();
});
});
describe('update', () => {
it('rolls back transaction when trigger throws except afterCommit', async () => {
const vc1 = new ViewerContext(
createKnexIntegrationTestEntityCompanionProvider(knexInstance)
);
const entity = await PostgresTriggerTestEntity.creator(vc1)
.setField('name', 'blah')
.enforceCreateAsync();
await expect(
PostgresTriggerTestEntity.updater(entity)
.setField('name', 'beforeUpdate')
.enforceUpdateAsync()
).rejects.toThrowError('name cannot have value beforeUpdate');
await expect(
PostgresTriggerTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'beforeUpdate')
).resolves.toBeNull();
await expect(
PostgresTriggerTestEntity.updater(entity)
.setField('name', 'afterUpdate')
.enforceUpdateAsync()
).rejects.toThrowError('name cannot have value afterUpdate');
await expect(
PostgresTriggerTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'afterUpdate')
).resolves.toBeNull();
await expect(
PostgresTriggerTestEntity.updater(entity)
.setField('name', 'beforeAll')
.enforceUpdateAsync()
).rejects.toThrowError('name cannot have value beforeAll');
await expect(
PostgresTriggerTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'beforeAll')
).resolves.toBeNull();
await expect(
PostgresTriggerTestEntity.updater(entity)
.setField('name', 'afterAll')
.enforceUpdateAsync()
).rejects.toThrowError('name cannot have value afterAll');
await expect(
PostgresTriggerTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'afterAll')
).resolves.toBeNull();
await expect(
PostgresTriggerTestEntity.updater(entity)
.setField('name', 'afterCommit')
.enforceUpdateAsync()
).rejects.toThrowError('name cannot have value afterCommit');
await expect(
PostgresTriggerTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'afterCommit')
).resolves.not.toBeNull();
});
});
describe('delete', () => {
it('rolls back transaction when trigger throws except afterCommit', async () => {
const vc1 = new ViewerContext(
createKnexIntegrationTestEntityCompanionProvider(knexInstance)
);
const entityBeforeDelete = await PostgresTriggerTestEntity.creator(vc1)
.setField('name', 'beforeDelete')
.enforceCreateAsync();
await expect(
PostgresTriggerTestEntity.enforceDeleteAsync(entityBeforeDelete)
).rejects.toThrowError('name cannot have value beforeDelete');
await expect(
PostgresTriggerTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'beforeDelete')
).resolves.not.toBeNull();
const entityAfterDelete = await PostgresTriggerTestEntity.creator(vc1)
.setField('name', 'afterDelete')
.enforceCreateAsync();
await expect(
PostgresTriggerTestEntity.enforceDeleteAsync(entityAfterDelete)
).rejects.toThrowError('name cannot have value afterDelete');
await expect(
PostgresTriggerTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'afterDelete')
).resolves.not.toBeNull();
});
});
describe('validation transaction behavior', () => {
describe('create', () => {
it('rolls back transaction when trigger throws ', async () => {
const vc1 = new ViewerContext(
createKnexIntegrationTestEntityCompanionProvider(knexInstance)
);
await expect(
PostgresValidatorTestEntity.creator(vc1)
.setField('name', 'beforeCreateAndBeforeUpdate')
.enforceCreateAsync()
).rejects.toThrowError('name cannot have value beforeCreateAndBeforeUpdate');
await expect(
PostgresValidatorTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'beforeCreateAndBeforeUpdate')
).resolves.toBeNull();
});
});
describe('update', () => {
it('rolls back transaction when trigger throws ', async () => {
const vc1 = new ViewerContext(
createKnexIntegrationTestEntityCompanionProvider(knexInstance)
);
const entity = await PostgresValidatorTestEntity.creator(vc1)
.setField('name', 'blah')
.enforceCreateAsync();
await expect(
PostgresValidatorTestEntity.updater(entity)
.setField('name', 'beforeCreateAndBeforeUpdate')
.enforceUpdateAsync()
).rejects.toThrowError('name cannot have value beforeCreateAndBeforeUpdate');
await expect(
PostgresValidatorTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'beforeCreateAndBeforeUpdate')
).resolves.toBeNull();
});
});
describe('delete', () => {
it('validation should not run on a delete mutation', async () => {
const vc1 = new ViewerContext(
createKnexIntegrationTestEntityCompanionProvider(knexInstance)
);
const entityToDelete = await PostgresValidatorTestEntity.creator(vc1)
.setField('name', 'shouldBeDeleted')
.enforceCreateAsync();
await PostgresValidatorTestEntity.enforceDeleteAsync(entityToDelete);
await expect(
PostgresValidatorTestEntity.loader(vc1)
.enforcing()
.loadByFieldEqualingAsync('name', 'shouldBeDeleted')
).resolves.toBeNull();
});
});
});
});
});
@@ -27,7 +27,7 @@ describe('postgres entity integration', () => {
afterAll(async () => {
await InvalidTestEntity.dropPostgresTable(knexInstance);
knexInstance.destroy();
await knexInstance.destroy();
});
describe('invalid operation result counts', () => {
@@ -43,9 +43,6 @@ describe('postgres entity integration', () => {
await expect(InvalidTestEntity.deleteAsync(entity1)).rejects.toThrowError(
'Excessive deletions from database adapter delete'
);
await expect(InvalidTestEntity.deleteAsync(entity1)).rejects.toThrowError(
'No deletions from database adapter delete'
);
});
it('throws after update of multiple rows', async () => {
@@ -0,0 +1,175 @@
import {
AlwaysAllowPrivacyPolicyRule,
EntityPrivacyPolicy,
ViewerContext,
UUIDField,
StringField,
EntityConfiguration,
DatabaseAdapterFlavor,
CacheAdapterFlavor,
EntityCompanionDefinition,
Entity,
EntityMutationTrigger,
EntityQueryContext,
EntityNonTransactionalMutationTrigger,
} from '@expo/entity';
import Knex from 'knex';
type PostgresTriggerTestEntityFields = {
id: string;
name: string | null;
};
export default class PostgresTriggerTestEntity extends Entity<
PostgresTriggerTestEntityFields,
string,
ViewerContext
> {
static getCompanionDefinition(): EntityCompanionDefinition<
PostgresTriggerTestEntityFields,
string,
ViewerContext,
PostgresTriggerTestEntity,
PostgresTriggerTestEntityPrivacyPolicy
> {
return postgresTestEntityCompanionDefinition;
}
public static async createOrTruncatePostgresTable(knex: Knex): Promise<void> {
await knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); // for uuid_generate_v4()
const tableName = this.getCompanionDefinition().entityConfiguration.tableName;
const hasTable = await knex.schema.hasTable(tableName);
if (!hasTable) {
await knex.schema.createTable(tableName, (table) => {
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
table.string('name');
});
}
await knex.into(tableName).truncate();
}
public static async dropPostgresTable(knex: Knex): Promise<void> {
const tableName = this.getCompanionDefinition().entityConfiguration.tableName;
const hasTable = await knex.schema.hasTable(tableName);
if (hasTable) {
await knex.schema.dropTable(tableName);
}
}
}
class PostgresTriggerTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
PostgresTriggerTestEntityFields,
string,
ViewerContext,
PostgresTriggerTestEntity
> {
protected readonly createRules = [
new AlwaysAllowPrivacyPolicyRule<
PostgresTriggerTestEntityFields,
string,
ViewerContext,
PostgresTriggerTestEntity
>(),
];
protected readonly readRules = [
new AlwaysAllowPrivacyPolicyRule<
PostgresTriggerTestEntityFields,
string,
ViewerContext,
PostgresTriggerTestEntity
>(),
];
protected readonly updateRules = [
new AlwaysAllowPrivacyPolicyRule<
PostgresTriggerTestEntityFields,
string,
ViewerContext,
PostgresTriggerTestEntity
>(),
];
protected readonly deleteRules = [
new AlwaysAllowPrivacyPolicyRule<
PostgresTriggerTestEntityFields,
string,
ViewerContext,
PostgresTriggerTestEntity
>(),
];
}
class ThrowConditionallyTrigger extends EntityMutationTrigger<
PostgresTriggerTestEntityFields,
string,
ViewerContext,
PostgresTriggerTestEntity
> {
constructor(private fieldName: keyof PostgresTriggerTestEntityFields, private badValue: string) {
super();
}
async executeAsync(
_viewerContext: ViewerContext,
_queryContext: EntityQueryContext,
entity: PostgresTriggerTestEntity
): Promise<void> {
if (entity.getField(this.fieldName) === this.badValue) {
throw new Error(`${this.fieldName} cannot have value ${this.badValue}`);
}
}
}
class ThrowConditionallyNonTransactionalTrigger extends EntityNonTransactionalMutationTrigger<
PostgresTriggerTestEntityFields,
string,
ViewerContext,
PostgresTriggerTestEntity
> {
constructor(private fieldName: keyof PostgresTriggerTestEntityFields, private badValue: string) {
super();
}
async executeAsync(
_viewerContext: ViewerContext,
entity: PostgresTriggerTestEntity
): Promise<void> {
if (entity.getField(this.fieldName) === this.badValue) {
throw new Error(`${this.fieldName} cannot have value ${this.badValue}`);
}
}
}
export const postgresTestEntityConfiguration = new EntityConfiguration<
PostgresTriggerTestEntityFields
>({
idField: 'id',
tableName: 'postgres_test_entities',
schema: {
id: new UUIDField({
columnName: 'id',
cache: true,
}),
name: new StringField({
columnName: 'name',
}),
},
databaseAdapterFlavor: DatabaseAdapterFlavor.POSTGRES,
cacheAdapterFlavor: CacheAdapterFlavor.REDIS,
});
const postgresTestEntityCompanionDefinition = new EntityCompanionDefinition({
entityClass: PostgresTriggerTestEntity,
entityConfiguration: postgresTestEntityConfiguration,
privacyPolicyClass: PostgresTriggerTestEntityPrivacyPolicy,
mutationTriggers: {
beforeCreate: [new ThrowConditionallyTrigger('name', 'beforeCreate')],
afterCreate: [new ThrowConditionallyTrigger('name', 'afterCreate')],
beforeUpdate: [new ThrowConditionallyTrigger('name', 'beforeUpdate')],
afterUpdate: [new ThrowConditionallyTrigger('name', 'afterUpdate')],
beforeDelete: [new ThrowConditionallyTrigger('name', 'beforeDelete')],
afterDelete: [new ThrowConditionallyTrigger('name', 'afterDelete')],
beforeAll: [new ThrowConditionallyTrigger('name', 'beforeAll')],
afterAll: [new ThrowConditionallyTrigger('name', 'afterAll')],
afterCommit: [new ThrowConditionallyNonTransactionalTrigger('name', 'afterCommit')],
},
});
@@ -0,0 +1,147 @@
import {
AlwaysAllowPrivacyPolicyRule,
EntityPrivacyPolicy,
ViewerContext,
UUIDField,
StringField,
EntityConfiguration,
DatabaseAdapterFlavor,
CacheAdapterFlavor,
EntityCompanionDefinition,
Entity,
EntityMutationTrigger,
EntityQueryContext,
} from '@expo/entity';
import Knex from 'knex';
type PostgresValidatorTestEntityFields = {
id: string;
name: string | null;
};
export default class PostgresValidatorTestEntity extends Entity<
PostgresValidatorTestEntityFields,
string,
ViewerContext
> {
static getCompanionDefinition(): EntityCompanionDefinition<
PostgresValidatorTestEntityFields,
string,
ViewerContext,
PostgresValidatorTestEntity,
PostgresValidatorTestEntityPrivacyPolicy
> {
return postgresTestEntityCompanionDefinition;
}
public static async createOrTruncatePostgresTable(knex: Knex): Promise<void> {
await knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); // for uuid_generate_v4()
const tableName = this.getCompanionDefinition().entityConfiguration.tableName;
const hasTable = await knex.schema.hasTable(tableName);
if (!hasTable) {
await knex.schema.createTable(tableName, (table) => {
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
table.string('name');
});
}
await knex.into(tableName).truncate();
}
public static async dropPostgresTable(knex: Knex): Promise<void> {
const tableName = this.getCompanionDefinition().entityConfiguration.tableName;
const hasTable = await knex.schema.hasTable(tableName);
if (hasTable) {
await knex.schema.dropTable(tableName);
}
}
}
class PostgresValidatorTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
PostgresValidatorTestEntityFields,
string,
ViewerContext,
PostgresValidatorTestEntity
> {
protected readonly createRules = [
new AlwaysAllowPrivacyPolicyRule<
PostgresValidatorTestEntityFields,
string,
ViewerContext,
PostgresValidatorTestEntity
>(),
];
protected readonly readRules = [
new AlwaysAllowPrivacyPolicyRule<
PostgresValidatorTestEntityFields,
string,
ViewerContext,
PostgresValidatorTestEntity
>(),
];
protected readonly updateRules = [
new AlwaysAllowPrivacyPolicyRule<
PostgresValidatorTestEntityFields,
string,
ViewerContext,
PostgresValidatorTestEntity
>(),
];
protected readonly deleteRules = [
new AlwaysAllowPrivacyPolicyRule<
PostgresValidatorTestEntityFields,
string,
ViewerContext,
PostgresValidatorTestEntity
>(),
];
}
class ThrowConditionallyTrigger extends EntityMutationTrigger<
PostgresValidatorTestEntityFields,
string,
ViewerContext,
PostgresValidatorTestEntity
> {
constructor(
private fieldName: keyof PostgresValidatorTestEntityFields,
private badValue: string
) {
super();
}
async executeAsync(
_viewerContext: ViewerContext,
_queryContext: EntityQueryContext,
entity: PostgresValidatorTestEntity
): Promise<void> {
if (entity.getField(this.fieldName) === this.badValue) {
throw new Error(`${this.fieldName} cannot have value ${this.badValue}`);
}
}
}
export const postgresTestEntityConfiguration = new EntityConfiguration<
PostgresValidatorTestEntityFields
>({
idField: 'id',
tableName: 'postgres_test_entities',
schema: {
id: new UUIDField({
columnName: 'id',
cache: true,
}),
name: new StringField({
columnName: 'name',
}),
},
databaseAdapterFlavor: DatabaseAdapterFlavor.POSTGRES,
cacheAdapterFlavor: CacheAdapterFlavor.REDIS,
});
const postgresTestEntityCompanionDefinition = new EntityCompanionDefinition({
entityClass: PostgresValidatorTestEntity,
entityConfiguration: postgresTestEntityConfiguration,
privacyPolicyClass: PostgresValidatorTestEntityPrivacyPolicy,
mutationValidators: [new ThrowConditionallyTrigger('name', 'beforeCreateAndBeforeUpdate')],
});
@@ -4,7 +4,7 @@ import {
EntityCompanionProvider,
CacheAdapterFlavor,
DatabaseAdapterFlavor,
NoCacheStubCacheAdapterProvider,
InMemoryFullCacheStubCacheAdapterProvider,
} from '@expo/entity';
import Knex from 'knex';
@@ -25,7 +25,7 @@ export const createKnexIntegrationTestEntityCompanionProvider = (
},
{
[CacheAdapterFlavor.REDIS]: {
cacheAdapterProvider: new NoCacheStubCacheAdapterProvider(),
cacheAdapterProvider: new InMemoryFullCacheStubCacheAdapterProvider(),
},
}
);
+76
View File
@@ -3,6 +3,82 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [0.10.0](https://github.com/expo/entity/compare/v0.9.1...v0.10.0) (2020-11-17)
**Note:** Version bump only for package @expo/entity-example
## [0.9.1](https://github.com/expo/entity/compare/v0.9.0...v0.9.1) (2020-11-06)
**Note:** Version bump only for package @expo/entity-example
# [0.9.0](https://github.com/expo/entity/compare/v0.8.1...v0.9.0) (2020-11-05)
**Note:** Version bump only for package @expo/entity-example
## [0.8.1](https://github.com/expo/entity/compare/v0.8.0...v0.8.1) (2020-10-09)
**Note:** Version bump only for package @expo/entity-example
# [0.8.0](https://github.com/expo/entity/compare/v0.7.1...v0.8.0) (2020-10-09)
**Note:** Version bump only for package @expo/entity-example
## [0.7.1](https://github.com/expo/entity/compare/v0.7.0...v0.7.1) (2020-10-01)
**Note:** Version bump only for package @expo/entity-example
# [0.7.0](https://github.com/expo/entity/compare/v0.6.0...v0.7.0) (2020-10-01)
### Bug Fixes
* move cache invalidation to after transaction commit ([#77](https://github.com/expo/entity/issues/77)) ([dbc3c81](https://github.com/expo/entity/commit/dbc3c81b359a668b5134189ce6de49b5893bb5e7))
* upgrade packages ([#78](https://github.com/expo/entity/issues/78)) ([9891e74](https://github.com/expo/entity/commit/9891e7469467a28589f529c8d87b10fc2232d3ff))
# [0.6.0](https://github.com/expo/entity/compare/v0.5.2...v0.6.0) (2020-07-23)
**Note:** Version bump only for package @expo/entity-example
## [0.5.2](https://github.com/expo/entity/compare/v0.5.1...v0.5.2) (2020-07-02)
**Note:** Version bump only for package @expo/entity-example
## [0.5.1](https://github.com/expo/entity/compare/v0.5.0...v0.5.1) (2020-07-01)
**Note:** Version bump only for package @expo/entity-example
+14 -14
View File
@@ -1,20 +1,20 @@
{
"name": "@expo/entity-example",
"private": true,
"version": "0.5.1",
"version": "0.10.0",
"description": "An example integration of the @expo/entity framework",
"scripts": {
"tsc": "tsc",
"clean": "rm -rf build coverage coverage-integration",
"lint": "eslint src --ext '.ts'",
"test": "jest --rootDir --config ../../resources/jest.config.js",
"test": "jest --rootDir . --config ../../resources/jest.config.js",
"integration": "../../resources/run-with-docker yarn integration-no-setup",
"integration-no-setup": "jest --config ../../resources/jest-integration.config.js --rootDir --runInBand --passWithNoTests",
"integration-no-setup": "jest --config ../../resources/jest-integration.config.js --rootDir . --runInBand --passWithNoTests",
"barrelsby": "barrelsby --directory src --location top --exclude tests__ --singleQuotes --exportDefault --delete",
"start": "tsnd --transpile-only --inspect --respawn --no-notify --async-stack-traces --throw-deprecation -- src/index.ts"
},
"engines": {
"node": ">=8"
"node": ">=12"
},
"keywords": [
"entity"
@@ -22,18 +22,18 @@
"author": "Expo",
"license": "MIT",
"dependencies": {
"@expo/entity": "^0.5.1",
"apollo-server-koa": "^2.14.2",
"graphql": "^15.0.0",
"koa": "^2.11.0",
"koa-body": "^4.1.1",
"koa-router": "^8.0.8"
"@expo/entity": "^0.10.0",
"apollo-server-koa": "^2.16.1",
"graphql": "^15.3.0",
"koa": "^2.13.0",
"koa-body": "^4.2.0",
"koa-router": "^9.4.0"
},
"devDependencies": {
"@types/koa": "^2.11.3",
"@types/koa-router": "^7.4.0",
"@types/supertest": "^2.0.9",
"@types/koa": "^2.11.4",
"@types/koa-router": "^7.4.1",
"@types/supertest": "^2.0.10",
"supertest": "^4.0.2",
"ts-node-dev": "^1.0.0-pre.44"
"ts-node-dev": "^1.0.0-pre.60"
}
}
@@ -1,18 +1,13 @@
import {
IEntityQueryContextProvider,
EntityQueryContext,
EntityNonTransactionalQueryContext,
EntityTransactionalQueryContext,
} from '@expo/entity';
import { EntityQueryContextProvider } from '@expo/entity';
export default class InMemoryQueryContextProvider implements IEntityQueryContextProvider {
getRegularEntityQueryContext(): EntityQueryContext {
return new EntityNonTransactionalQueryContext({});
export default class InMemoryQueryContextProvider extends EntityQueryContextProvider {
protected getQueryInterface(): any {
return {};
}
async runInTransactionAsync<T>(
transactionScope: (queryContext: EntityQueryContext) => Promise<T>
): Promise<T> {
return await transactionScope(new EntityTransactionalQueryContext({}));
protected createTransactionRunner<T>(): (
transactionScope: (queryInterface: any) => Promise<T>
) => Promise<T> {
return (transactionScope) => Promise.resolve(transactionScope({}));
}
}
+2 -2
View File
@@ -2,14 +2,14 @@ import { EntityCompanionProvider } from '@expo/entity';
import { ApolloServer } from 'apollo-server-koa';
import Koa from 'koa';
import koaBody from 'koa-body';
import KoaRouter from 'koa-router';
import KoaRouter, { RouterContext } from 'koa-router';
import { entityCompanionMiddleware, viewerContextMiddleware } from './middleware';
import notesRouter from './routers/notesRouter';
import { typeDefs, resolvers } from './schema';
import { ExampleViewerContext } from './viewerContexts';
export type ExampleContext = Koa.ParameterizedContext<ExampleState>;
export type ExampleContext = RouterContext<ExampleState>;
/**
* Koa provides a per-request state container to place custom properties.
@@ -0,0 +1,66 @@
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [0.10.0](https://github.com/expo/entity/compare/v0.9.1...v0.10.0) (2020-11-17)
**Note:** Version bump only for package @expo/entity-full-integration-tests
## [0.9.1](https://github.com/expo/entity/compare/v0.9.0...v0.9.1) (2020-11-06)
### Bug Fixes
* edge deletion behavior cyclic import structure again ([#93](https://github.com/expo/entity/issues/93)) ([012c05d](https://github.com/expo/entity/commit/012c05d62d2ecd559eb331c6ca358052bfe66dc8))
# [0.9.0](https://github.com/expo/entity/compare/v0.8.1...v0.9.0) (2020-11-05)
### Bug Fixes
* edge deletion behavior cyclic import structure ([#89](https://github.com/expo/entity/issues/89)) ([cca8fc1](https://github.com/expo/entity/commit/cca8fc19870057ebc7033081b59fab4a142fbf1a))
## [0.8.1](https://github.com/expo/entity/compare/v0.8.0...v0.8.1) (2020-10-09)
**Note:** Version bump only for package @expo/entity-full-integration-tests
# [0.8.0](https://github.com/expo/entity/compare/v0.7.1...v0.8.0) (2020-10-09)
**Note:** Version bump only for package @expo/entity-full-integration-tests
## [0.7.1](https://github.com/expo/entity/compare/v0.7.0...v0.7.1) (2020-10-01)
**Note:** Version bump only for package @expo/entity-full-integration-tests
# [0.7.0](https://github.com/expo/entity/compare/v0.6.0...v0.7.0) (2020-10-01)
### Bug Fixes
* move cache invalidation to after transaction commit ([#77](https://github.com/expo/entity/issues/77)) ([dbc3c81](https://github.com/expo/entity/commit/dbc3c81b359a668b5134189ce6de49b5893bb5e7))
* upgrade packages ([#78](https://github.com/expo/entity/issues/78)) ([9891e74](https://github.com/expo/entity/commit/9891e7469467a28589f529c8d87b10fc2232d3ff))
@@ -0,0 +1,5 @@
# `@expo/entity-full-integration-tests`
Full integration tests for testing combinations of database and cache adapters.
[Documentation](https://expo.github.io/entity/modules/_expo_entity_full_integration_tests.html)
@@ -0,0 +1,33 @@
{
"name": "@expo/entity-full-integration-tests",
"private": true,
"version": "0.10.0",
"description": "Full redis and knex integration tests for the entity framework",
"scripts": {
"tsc": "tsc",
"clean": "rm -rf build coverage coverage-integration",
"lint": "eslint src --ext '.ts'",
"test": "jest --rootDir . --config ../../resources/jest.config.js --passWithNoTests",
"integration": "../../resources/run-with-docker yarn integration-no-setup",
"integration-no-setup": "jest --config ../../resources/jest-integration.config.js --rootDir . --runInBand --passWithNoTests",
"barrelsby": "barrelsby --directory src --location top --exclude tests__ --singleQuotes --exportDefault --delete"
},
"engines": {
"node": ">=12"
},
"keywords": [
"entity"
],
"author": "Expo",
"license": "MIT",
"peerDependencies": {
"@expo/entity": "*",
"@expo/entity-cache-adapter-redis": "*",
"@expo/entity-database-adapter-knex": "*"
},
"devDependencies": {
"@expo/entity": "^0.10.0",
"@expo/entity-cache-adapter-redis": "^0.10.0",
"@expo/entity-database-adapter-knex": "^0.10.0"
}
}
@@ -0,0 +1,205 @@
import {
EntityPrivacyPolicy,
ViewerContext,
AlwaysAllowPrivacyPolicyRule,
Entity,
EntityCompanionDefinition,
EntityConfiguration,
DatabaseAdapterFlavor,
CacheAdapterFlavor,
UUIDField,
} from '@expo/entity';
import { RedisCacheAdapterContext } from '@expo/entity-cache-adapter-redis';
import Redis from 'ioredis';
import Knex from 'knex';
import { URL } from 'url';
import { createFullIntegrationTestEntityCompanionProvider } from '../testfixtures/createFullIntegrationTestEntityCompanionProvider';
interface TestFields {
id: string;
other_string: string;
third_string: string;
}
class TestEntityPrivacyPolicy extends EntityPrivacyPolicy<
TestFields,
string,
ViewerContext,
TestEntity
> {
protected readonly readRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly createRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly updateRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly deleteRules = [new AlwaysAllowPrivacyPolicyRule()];
}
class TestEntity extends Entity<TestFields, string, ViewerContext> {
static getCompanionDefinition(): EntityCompanionDefinition<
TestFields,
string,
ViewerContext,
TestEntity,
TestEntityPrivacyPolicy
> {
return testEntityCompanion;
}
}
const testEntityConfiguration = new EntityConfiguration<TestFields>({
idField: 'id',
tableName: 'testentities',
schema: {
id: new UUIDField({
columnName: 'id',
cache: true,
}),
other_string: new UUIDField({
columnName: 'other_string',
cache: true,
}),
third_string: new UUIDField({
columnName: 'third_string',
}),
},
databaseAdapterFlavor: DatabaseAdapterFlavor.POSTGRES,
cacheAdapterFlavor: CacheAdapterFlavor.REDIS,
});
const testEntityCompanion = new EntityCompanionDefinition({
entityClass: TestEntity,
entityConfiguration: testEntityConfiguration,
privacyPolicyClass: TestEntityPrivacyPolicy,
});
async function createOrTruncatePostgresTables(knex: Knex): Promise<void> {
await knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); // for uuid_generate_v4()
await knex.schema.createTable('testentities', (table) => {
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
table.string('other_string').notNullable();
table.string('third_string').notNullable();
});
await knex.into('testentities').truncate();
}
async function dropPostgresTable(knex: Knex): Promise<void> {
if (await knex.schema.hasTable('children')) {
await knex.schema.dropTable('children');
}
if (await knex.schema.hasTable('parents')) {
await knex.schema.dropTable('parents');
}
}
describe('Entity cache inconsistency', () => {
let knexInstance: Knex;
let redisCacheAdapterContext: RedisCacheAdapterContext;
beforeAll(() => {
knexInstance = Knex({
client: 'pg',
connection: {
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
host: 'localhost',
port: parseInt(process.env.PGPORT!, 10),
database: process.env.PGDATABASE,
},
});
redisCacheAdapterContext = {
redisClient: new Redis(new URL(process.env.REDIS_URL!).toString()),
makeKeyFn(...parts: string[]): string {
const delimiter = ':';
const escapedParts = parts.map((part) =>
part.replace('\\', '\\\\').replace(delimiter, `\\${delimiter}`)
);
return escapedParts.join(delimiter);
},
cacheKeyPrefix: 'test-',
cacheKeyVersion: 1,
ttlSecondsPositive: 86400, // 1 day
ttlSecondsNegative: 600, // 10 minutes
};
});
beforeEach(async () => {
await createOrTruncatePostgresTables(knexInstance);
await redisCacheAdapterContext.redisClient.flushdb();
});
afterAll(async () => {
await dropPostgresTable(knexInstance);
await knexInstance.destroy();
redisCacheAdapterContext.redisClient.disconnect();
});
test('lots of updates in long-ish running transactions', async () => {
const viewerContext = new ViewerContext(
createFullIntegrationTestEntityCompanionProvider(knexInstance, redisCacheAdapterContext)
);
const entity1 = await TestEntity.creator(viewerContext)
.setField('other_string', 'hello')
.setField('third_string', 'initial')
.enforceCreateAsync();
// put entities in cache and dataloader
await TestEntity.loader(viewerContext).enforcing().loadByIDAsync(entity1.getID());
await TestEntity.loader(viewerContext)
.enforcing()
.loadByFieldEqualingAsync('other_string', 'hello');
let openBarrier1: () => void;
const barrier1 = new Promise((resolve) => {
openBarrier1 = resolve;
});
let openBarrier2: () => void;
const barrier2 = new Promise((resolve) => {
openBarrier2 = resolve;
});
await Promise.all([
// do a load after the transaction below updates the entity but before transaction commits to ensure
// that the cache is cleared after the transaction commits rather than in the middle where the changes
// may not be visible by other requests (ViewerContexts) which would cache the incorrect
// value during the read-through cache.
(async () => {
await barrier1;
const viewerContextInternal = new ViewerContext(
createFullIntegrationTestEntityCompanionProvider(knexInstance, redisCacheAdapterContext)
);
await TestEntity.loader(viewerContextInternal).enforcing().loadByIDAsync(entity1.getID());
openBarrier2!();
})(),
TestEntity.runInTransactionAsync(viewerContext, async (queryContext) => {
await TestEntity.updater(entity1, queryContext)
.setField('third_string', 'updated')
.enforceUpdateAsync();
openBarrier1();
// wait for to ensure the transaction isn't committed until after load above occurs
await barrier2;
}),
]);
// ensure cache consistency
const viewerContextLast = new ViewerContext(
createFullIntegrationTestEntityCompanionProvider(knexInstance, redisCacheAdapterContext)
);
const loadedById = await TestEntity.loader(viewerContextLast)
.enforcing()
.loadByIDAsync(entity1.getID());
const loadedByField = await TestEntity.loader(viewerContextLast)
.enforcing()
.loadByFieldEqualingAsync('other_string', 'hello');
expect(loadedById.getField('third_string')).toEqual('updated');
expect(loadedByField!.getField('third_string')).toEqual('updated');
});
});
@@ -0,0 +1,108 @@
import { ViewerContext } from '@expo/entity';
import { RedisCacheAdapterContext } from '@expo/entity-cache-adapter-redis';
import Redis from 'ioredis';
import Knex from 'knex';
import { URL } from 'url';
import { createFullIntegrationTestEntityCompanionProvider } from '../testfixtures/createFullIntegrationTestEntityCompanionProvider';
import ChildEntity from './entities/ChildEntity';
import ParentEntity from './entities/ParentEntity';
async function createOrTruncatePostgresTables(knex: Knex): Promise<void> {
await knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); // for uuid_generate_v4()
await knex.schema.createTable('parents', (table) => {
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
});
await knex.into('parents').truncate();
await knex.schema.createTable('children', (table) => {
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
table.uuid('parent_id').references('id').inTable('parents').onDelete('cascade').unique();
});
await knex.into('children').truncate();
}
async function dropPostgresTable(knex: Knex): Promise<void> {
if (await knex.schema.hasTable('children')) {
await knex.schema.dropTable('children');
}
if (await knex.schema.hasTable('parents')) {
await knex.schema.dropTable('parents');
}
}
describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
let knexInstance: Knex;
let redisCacheAdapterContext: RedisCacheAdapterContext;
beforeAll(() => {
knexInstance = Knex({
client: 'pg',
connection: {
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
host: 'localhost',
port: parseInt(process.env.PGPORT!, 10),
database: process.env.PGDATABASE,
},
});
redisCacheAdapterContext = {
redisClient: new Redis(new URL(process.env.REDIS_URL!).toString()),
makeKeyFn(...parts: string[]): string {
const delimiter = ':';
const escapedParts = parts.map((part) =>
part.replace('\\', '\\\\').replace(delimiter, `\\${delimiter}`)
);
return escapedParts.join(delimiter);
},
cacheKeyPrefix: 'test-',
cacheKeyVersion: 1,
ttlSecondsPositive: 86400, // 1 day
ttlSecondsNegative: 600, // 10 minutes
};
});
beforeEach(async () => {
await createOrTruncatePostgresTables(knexInstance);
await redisCacheAdapterContext.redisClient.flushdb();
});
afterAll(async () => {
await dropPostgresTable(knexInstance);
await knexInstance.destroy();
redisCacheAdapterContext.redisClient.disconnect();
});
describe('EntityEdgeDeletionBehavior.INVALIDATE_CACHE', () => {
it('invalidates the cache', async () => {
const viewerContext = new ViewerContext(
createFullIntegrationTestEntityCompanionProvider(knexInstance, redisCacheAdapterContext)
);
const parent = await ParentEntity.creator(viewerContext).enforceCreateAsync();
const child = await ChildEntity.creator(viewerContext)
.setField('parent_id', parent.getID())
.enforceCreateAsync();
await expect(
ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID())
).resolves.not.toBeNull();
await expect(
ChildEntity.loader(viewerContext)
.enforcing()
.loadByFieldEqualingAsync('parent_id', parent.getID())
).resolves.not.toBeNull();
await ParentEntity.enforceDeleteAsync(parent);
await expect(
ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID())
).resolves.toBeNull();
await expect(
ChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(child.getID())
).resolves.toBeNull();
});
});
});
@@ -0,0 +1,235 @@
import {
EntityPrivacyPolicy,
ViewerContext,
AlwaysAllowPrivacyPolicyRule,
Entity,
EntityCompanionDefinition,
EntityConfiguration,
DatabaseAdapterFlavor,
CacheAdapterFlavor,
UUIDField,
EntityEdgeDeletionBehavior,
} from '@expo/entity';
import { RedisCacheAdapterContext } from '@expo/entity-cache-adapter-redis';
import Redis from 'ioredis';
import Knex from 'knex';
import { URL } from 'url';
import { v4 as uuidv4 } from 'uuid';
import { createFullIntegrationTestEntityCompanionProvider } from '../testfixtures/createFullIntegrationTestEntityCompanionProvider';
interface CategoryFields {
id: string;
parent_other_id: string;
}
interface OtherFields {
id: string;
parent_category_id: string;
}
class PrivacyPolicy extends EntityPrivacyPolicy<any, string, ViewerContext, any> {
protected readonly readRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly createRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly updateRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly deleteRules = [new AlwaysAllowPrivacyPolicyRule()];
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const makeEntityClasses = async (knex: Knex, edgeDeletionBehavior: EntityEdgeDeletionBehavior) => {
const categoriesTableName = uuidv4();
const othersTableName = uuidv4();
class CategoryEntity extends Entity<CategoryFields, string, ViewerContext> {
static getCompanionDefinition(): EntityCompanionDefinition<
CategoryFields,
string,
ViewerContext,
CategoryEntity,
PrivacyPolicy
> {
return categoryEntityCompanion;
}
}
class OtherEntity extends Entity<OtherFields, string, ViewerContext> {
static getCompanionDefinition(): EntityCompanionDefinition<
OtherFields,
string,
ViewerContext,
OtherEntity,
PrivacyPolicy
> {
return otherEntityCompanion;
}
}
const categoryEntityConfiguration = new EntityConfiguration<CategoryFields>({
idField: 'id',
tableName: categoriesTableName,
getInboundEdges: () => [OtherEntity],
schema: {
id: new UUIDField({
columnName: 'id',
cache: true,
}),
parent_other_id: new UUIDField({
columnName: 'parent_other_id',
cache: true,
association: {
getAssociatedEntityClass: () => OtherEntity,
edgeDeletionBehavior,
},
}),
},
databaseAdapterFlavor: DatabaseAdapterFlavor.POSTGRES,
cacheAdapterFlavor: CacheAdapterFlavor.REDIS,
});
const categoryEntityCompanion = new EntityCompanionDefinition({
entityClass: CategoryEntity,
entityConfiguration: categoryEntityConfiguration,
privacyPolicyClass: PrivacyPolicy,
});
const otherEntityConfiguration = new EntityConfiguration<OtherFields>({
idField: 'id',
tableName: othersTableName,
getInboundEdges: () => [CategoryEntity],
schema: {
id: new UUIDField({
columnName: 'id',
cache: true,
}),
parent_category_id: new UUIDField({
columnName: 'parent_category_id',
cache: true,
association: {
getAssociatedEntityClass: () => CategoryEntity,
edgeDeletionBehavior,
},
}),
},
databaseAdapterFlavor: DatabaseAdapterFlavor.POSTGRES,
cacheAdapterFlavor: CacheAdapterFlavor.REDIS,
});
const otherEntityCompanion = new EntityCompanionDefinition({
entityClass: OtherEntity,
entityConfiguration: otherEntityConfiguration,
privacyPolicyClass: PrivacyPolicy,
});
await knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); // for uuid_generate_v4()
await knex.schema.createTable(categoriesTableName, (table) => {
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
});
await knex.schema.createTable(othersTableName, (table) => {
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
if (edgeDeletionBehavior === EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE) {
table
.uuid('parent_category_id')
.references('id')
.inTable(categoriesTableName)
.unique()
.onDelete('cascade');
} else {
table.uuid('parent_category_id').unique();
}
});
await knex.schema.alterTable(categoriesTableName, (table) => {
if (edgeDeletionBehavior === EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE) {
table
.uuid('parent_other_id')
.references('id')
.inTable(othersTableName)
.unique()
.onDelete('cascade');
} else {
table.uuid('parent_other_id').unique();
}
});
return { CategoryEntity, OtherEntity };
};
describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
let knexInstance: Knex;
let redisCacheAdapterContext: RedisCacheAdapterContext;
beforeAll(() => {
knexInstance = Knex({
client: 'pg',
connection: {
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
host: 'localhost',
port: parseInt(process.env.PGPORT!, 10),
database: process.env.PGDATABASE,
},
});
redisCacheAdapterContext = {
redisClient: new Redis(new URL(process.env.REDIS_URL!).toString()),
makeKeyFn(...parts: string[]): string {
const delimiter = ':';
const escapedParts = parts.map((part) =>
part.replace('\\', '\\\\').replace(delimiter, `\\${delimiter}`)
);
return escapedParts.join(delimiter);
},
cacheKeyPrefix: 'test-',
cacheKeyVersion: 1,
ttlSecondsPositive: 86400, // 1 day
ttlSecondsNegative: 600, // 10 minutes
};
});
afterAll(async () => {
await knexInstance.destroy();
redisCacheAdapterContext.redisClient.disconnect();
});
it.each([
EntityEdgeDeletionBehavior.CASCADE_DELETE,
EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE,
EntityEdgeDeletionBehavior.SET_NULL,
])('behavior: %p', async (edgeDeletionBehavior) => {
const { CategoryEntity, OtherEntity } = await makeEntityClasses(
knexInstance,
edgeDeletionBehavior
);
const viewerContext = new ViewerContext(
createFullIntegrationTestEntityCompanionProvider(knexInstance, redisCacheAdapterContext)
);
const category1 = await CategoryEntity.creator(viewerContext).enforceCreateAsync();
const other1 = await OtherEntity.creator(viewerContext)
.setField('parent_category_id', category1.getID())
.enforceCreateAsync();
await CategoryEntity.updater(category1)
.setField('parent_other_id', other1.getID())
.enforceUpdateAsync();
await CategoryEntity.enforceDeleteAsync(category1);
if (edgeDeletionBehavior === EntityEdgeDeletionBehavior.SET_NULL) {
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(category1.getID())
).resolves.toBeNull();
const otherLoaded = await OtherEntity.loader(viewerContext)
.enforcing()
.loadByIDNullableAsync(other1.getID());
expect(otherLoaded?.getField('parent_category_id')).toBeNull();
} else {
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(category1.getID())
).resolves.toBeNull();
await expect(
OtherEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(other1.getID())
).resolves.toBeNull();
}
});
});
@@ -0,0 +1,65 @@
import {
AlwaysAllowPrivacyPolicyRule,
CacheAdapterFlavor,
DatabaseAdapterFlavor,
Entity,
EntityCompanionDefinition,
EntityConfiguration,
EntityEdgeDeletionBehavior,
EntityPrivacyPolicy,
UUIDField,
ViewerContext,
} from '@expo/entity';
import ParentEntity from './ParentEntity';
interface ChildFields {
id: string;
parent_id: string;
}
class TestEntityPrivacyPolicy extends EntityPrivacyPolicy<any, string, ViewerContext, any, any> {
protected readonly readRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly createRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly updateRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly deleteRules = [new AlwaysAllowPrivacyPolicyRule()];
}
export default class ChildEntity extends Entity<ChildFields, string, ViewerContext> {
static getCompanionDefinition(): EntityCompanionDefinition<
ChildFields,
string,
ViewerContext,
ChildEntity,
TestEntityPrivacyPolicy
> {
return childEntityCompanion;
}
}
const childEntityConfiguration = new EntityConfiguration<ChildFields>({
idField: 'id',
tableName: 'children',
schema: {
id: new UUIDField({
columnName: 'id',
cache: true,
}),
parent_id: new UUIDField({
columnName: 'parent_id',
cache: true,
association: {
getAssociatedEntityClass: () => ParentEntity,
edgeDeletionBehavior: EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE,
},
}),
},
databaseAdapterFlavor: DatabaseAdapterFlavor.POSTGRES,
cacheAdapterFlavor: CacheAdapterFlavor.REDIS,
});
const childEntityCompanion = new EntityCompanionDefinition({
entityClass: ChildEntity,
entityConfiguration: childEntityConfiguration,
privacyPolicyClass: TestEntityPrivacyPolicy,
});
@@ -0,0 +1,56 @@
import {
AlwaysAllowPrivacyPolicyRule,
CacheAdapterFlavor,
DatabaseAdapterFlavor,
Entity,
EntityCompanionDefinition,
EntityConfiguration,
EntityPrivacyPolicy,
UUIDField,
ViewerContext,
} from '@expo/entity';
import ChildEntity from './ChildEntity';
interface ParentFields {
id: string;
}
class TestEntityPrivacyPolicy extends EntityPrivacyPolicy<any, string, ViewerContext, any, any> {
protected readonly readRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly createRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly updateRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly deleteRules = [new AlwaysAllowPrivacyPolicyRule()];
}
export default class ParentEntity extends Entity<ParentFields, string, ViewerContext> {
static getCompanionDefinition(): EntityCompanionDefinition<
ParentFields,
string,
ViewerContext,
ParentEntity,
TestEntityPrivacyPolicy
> {
return parentEntityCompanion;
}
}
const parentEntityConfiguration = new EntityConfiguration<ParentFields>({
idField: 'id',
tableName: 'parents',
getInboundEdges: () => [ChildEntity],
schema: {
id: new UUIDField({
columnName: 'id',
cache: true,
}),
},
databaseAdapterFlavor: DatabaseAdapterFlavor.POSTGRES,
cacheAdapterFlavor: CacheAdapterFlavor.REDIS,
});
const parentEntityCompanion = new EntityCompanionDefinition({
entityClass: ParentEntity,
entityConfiguration: parentEntityConfiguration,
privacyPolicyClass: TestEntityPrivacyPolicy,
});
@@ -0,0 +1,37 @@
import {
NoOpEntityMetricsAdapter,
IEntityMetricsAdapter,
EntityCompanionProvider,
CacheAdapterFlavor,
DatabaseAdapterFlavor,
} from '@expo/entity';
import {
RedisCacheAdapterContext,
RedisCacheAdapterProvider,
} from '@expo/entity-cache-adapter-redis';
import {
PostgresEntityDatabaseAdapterProvider,
PostgresEntityQueryContextProvider,
} from '@expo/entity-database-adapter-knex';
import Knex from 'knex';
export const createFullIntegrationTestEntityCompanionProvider = (
knex: Knex,
redisCacheAdapterContext: RedisCacheAdapterContext,
metricsAdapter: IEntityMetricsAdapter = new NoOpEntityMetricsAdapter()
): EntityCompanionProvider => {
return new EntityCompanionProvider(
metricsAdapter,
{
[DatabaseAdapterFlavor.POSTGRES]: {
adapterProvider: new PostgresEntityDatabaseAdapterProvider(),
queryContextProvider: new PostgresEntityQueryContextProvider(knex),
},
},
{
[CacheAdapterFlavor.REDIS]: {
cacheAdapterProvider: new RedisCacheAdapterProvider(redisCacheAdapterContext),
},
}
);
};
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"noEmit": true,
},
"include": ["src"]
}
+112
View File
@@ -3,6 +3,118 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [0.10.0](https://github.com/expo/entity/compare/v0.9.1...v0.10.0) (2020-11-17)
### Bug Fixes
* fix null handling in load paths (try 2) ([#96](https://github.com/expo/entity/issues/96)) ([d960329](https://github.com/expo/entity/commit/d9603298e0cc5c3c2b0cca959876e9195555fb57))
## [0.9.1](https://github.com/expo/entity/compare/v0.9.0...v0.9.1) (2020-11-06)
### Bug Fixes
* edge deletion behavior cyclic import structure again ([#93](https://github.com/expo/entity/issues/93)) ([012c05d](https://github.com/expo/entity/commit/012c05d62d2ecd559eb331c6ca358052bfe66dc8))
# [0.9.0](https://github.com/expo/entity/compare/v0.8.1...v0.9.0) (2020-11-05)
### Bug Fixes
* edge deletion behavior cyclic import structure ([#89](https://github.com/expo/entity/issues/89)) ([cca8fc1](https://github.com/expo/entity/commit/cca8fc19870057ebc7033081b59fab4a142fbf1a))
### Features
* add ability to invalidate an entity manually ([#91](https://github.com/expo/entity/issues/91)) ([d1a6f13](https://github.com/expo/entity/commit/d1a6f1339648942f12b3fb605eb329aefe5cdd63))
## [0.8.1](https://github.com/expo/entity/compare/v0.8.0...v0.8.1) (2020-10-09)
**Note:** Version bump only for package @expo/entity
# [0.8.0](https://github.com/expo/entity/compare/v0.7.1...v0.8.0) (2020-10-09)
### Features
* add entityClassName to metrics adapter events ([#83](https://github.com/expo/entity/issues/83)) ([f4cdc01](https://github.com/expo/entity/commit/f4cdc01c6cb8868c24ce3da2274f0901687e05bd))
## [0.7.1](https://github.com/expo/entity/compare/v0.7.0...v0.7.1) (2020-10-01)
### Bug Fixes
* correct type of runInTransactionAsync ([#81](https://github.com/expo/entity/issues/81)) ([f98f7d1](https://github.com/expo/entity/commit/f98f7d14b6149a496a7a3e97dd63d89b2842cc26))
# [0.7.0](https://github.com/expo/entity/compare/v0.6.0...v0.7.0) (2020-10-01)
### Bug Fixes
* fix incorrect loader types for field selecitons ([#72](https://github.com/expo/entity/issues/72)) ([cd2df8d](https://github.com/expo/entity/commit/cd2df8da4b81bcd4769e950d3124c18886df2816))
* fix index export for EntityMutationTrigger and EntityMutationValidator ([#73](https://github.com/expo/entity/issues/73)) ([7e829f3](https://github.com/expo/entity/commit/7e829f30fde0bd343cb8a584ccda5530cf61ec33))
* move cache invalidation to after transaction commit ([#77](https://github.com/expo/entity/issues/77)) ([dbc3c81](https://github.com/expo/entity/commit/dbc3c81b359a668b5134189ce6de49b5893bb5e7))
* upgrade packages ([#78](https://github.com/expo/entity/issues/78)) ([9891e74](https://github.com/expo/entity/commit/9891e7469467a28589f529c8d87b10fc2232d3ff))
# [0.6.0](https://github.com/expo/entity/compare/v0.5.2...v0.6.0) (2020-07-23)
### Bug Fixes
* ensure transitive deletion triggers are run for CASCADE_DELETE_INVALIDATE_CACHE ([#66](https://github.com/expo/entity/issues/66)) ([5744c51](https://github.com/expo/entity/commit/5744c51e6b3178bd9f229f3f465b683bb4474c8a))
* separate out EntityMutationValidator ([#68](https://github.com/expo/entity/issues/68)) ([547a1ef](https://github.com/expo/entity/commit/547a1efcecd17cc085702d1a3e9888ce5b644b13))
* update setField to correct typing ([#62](https://github.com/expo/entity/issues/62)) ([7a77afc](https://github.com/expo/entity/commit/7a77afc83ea732c9b062a5d6865eff9d3131d015))
### Features
* entity mutation validators ([#67](https://github.com/expo/entity/issues/67)) ([fc4377d](https://github.com/expo/entity/commit/fc4377d8839da07417b88afc138f73556383d896))
* mutation triggers ([#65](https://github.com/expo/entity/issues/65)) ([fd6060c](https://github.com/expo/entity/commit/fd6060cc844f60635b3ce4c400c4877f2df8fa44))
## [0.5.2](https://github.com/expo/entity/compare/v0.5.1...v0.5.2) (2020-07-02)
### Bug Fixes
* fix stub cache key generation for global cache ([#59](https://github.com/expo/entity/issues/59)) ([7c180e8](https://github.com/expo/entity/commit/7c180e84d9a8cdfd9380fac0eab2d02a96ec18f3))
## [0.5.1](https://github.com/expo/entity/compare/v0.5.0...v0.5.1) (2020-07-01)
+6 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@expo/entity",
"version": "0.5.1",
"version": "0.10.0",
"description": "A privacy-first data model",
"files": [
"build",
@@ -12,13 +12,13 @@
"tsc": "tsc",
"clean": "rm -rf build coverage coverage-integration",
"lint": "eslint src --ext '.ts'",
"test": "jest --rootDir --config ../../resources/jest.config.js",
"test": "jest --rootDir . --config ../../resources/jest.config.js",
"integration": "../../resources/run-with-docker yarn integration-no-setup",
"integration-no-setup": "jest --config ../../resources/jest-integration.config.js --rootDir --runInBand --passWithNoTests",
"integration-no-setup": "jest --config ../../resources/jest-integration.config.js --rootDir . --runInBand --passWithNoTests",
"barrelsby": "barrelsby --directory src --location top --exclude tests__ --singleQuotes --exportDefault --delete"
},
"engines": {
"node": ">=8"
"node": ">=12"
},
"keywords": [
"entity"
@@ -26,11 +26,10 @@
"author": "Expo",
"license": "MIT",
"dependencies": {
"@expo/results": "^0.3.0",
"@expo/results": "^1.0.0",
"dataloader": "^2.0.0",
"es6-error": "^4.1.1",
"invariant": "^2.2.4",
"lodash": "^4.17.15",
"uuid": "^7.0.3"
"uuid": "^8.3.0"
}
}
+4 -4
View File
@@ -38,7 +38,7 @@ export default class EnforcingEntityLoader<
* Enforcing version of entity loader method by the same name.
* @throws {@link EntityNotAuthorizedError} when viewer is not authorized to view one or more of the returned entities
*/
async loadManyByFieldEqualingManyAsync<N extends keyof TFields>(
async loadManyByFieldEqualingManyAsync<N extends keyof Pick<TFields, TSelectedFields>>(
fieldName: N,
fieldValues: readonly NonNullable<TFields[N]>[]
): Promise<ReadonlyMap<NonNullable<TFields[N]>, readonly TEntity[]>> {
@@ -55,7 +55,7 @@ export default class EnforcingEntityLoader<
* Enforcing version of entity loader method by the same name.
* @throws {@link EntityNotAuthorizedError} when viewer is not authorized to view one or more of the returned entities
*/
async loadManyByFieldEqualingAsync<N extends keyof TFields>(
async loadManyByFieldEqualingAsync<N extends keyof Pick<TFields, TSelectedFields>>(
fieldName: N,
fieldValue: NonNullable<TFields[N]>
): Promise<readonly TEntity[]> {
@@ -71,7 +71,7 @@ export default class EnforcingEntityLoader<
* @throws {@link EntityNotAuthorizedError} when viewer is not authorized to view the returned entity
* @throws when multiple entities are found matching the condition
*/
async loadByFieldEqualingAsync<N extends keyof TFields>(
async loadByFieldEqualingAsync<N extends keyof Pick<TFields, TSelectedFields>>(
uniqueFieldName: N,
fieldValue: NonNullable<TFields[N]>
): Promise<TEntity | null> {
@@ -114,7 +114,7 @@ export default class EnforcingEntityLoader<
* Enforcing version of entity loader method by the same name.
* @throws {@link EntityNotAuthorizedError} when viewer is not authorized to view one or more of the returned entities
*/
async loadManyByFieldEqualityConjunctionAsync<N extends keyof TFields>(
async loadManyByFieldEqualityConjunctionAsync<N extends keyof Pick<TFields, TSelectedFields>>(
fieldEqualityOperands: FieldEqualityCondition<TFields, N>[],
querySelectionModifiers: QuerySelectionModifiers<TFields> = {}
): Promise<readonly TEntity[]> {
+6 -6
View File
@@ -64,7 +64,7 @@ export default abstract class Entity<
queryContext: EntityQueryContext = viewerContext
.getViewerScopedEntityCompanionForClass(this)
.getQueryContextProvider()
.getRegularEntityQueryContext()
.getQueryContext()
): CreateMutator<TMFields, TMID, TMViewerContext, TMEntity, TMPrivacyPolicy, TMSelectedFields> {
return viewerContext
.getViewerScopedEntityCompanionForClass(this)
@@ -105,7 +105,7 @@ export default abstract class Entity<
.getViewerContext()
.getViewerScopedEntityCompanionForClass(this)
.getQueryContextProvider()
.getRegularEntityQueryContext()
.getQueryContext()
): UpdateMutator<TMFields, TMID, TMViewerContext, TMEntity, TMPrivacyPolicy, TMSelectedFields> {
return existingEntity
.getViewerContext()
@@ -146,7 +146,7 @@ export default abstract class Entity<
.getViewerContext()
.getViewerScopedEntityCompanionForClass(this)
.getQueryContextProvider()
.getRegularEntityQueryContext()
.getQueryContext()
): Promise<Result<void>> {
return existingEntity
.getViewerContext()
@@ -188,7 +188,7 @@ export default abstract class Entity<
.getViewerContext()
.getViewerScopedEntityCompanionForClass(this)
.getQueryContextProvider()
.getRegularEntityQueryContext()
.getQueryContext()
): Promise<void> {
return existingEntity
.getViewerContext()
@@ -241,7 +241,7 @@ export default abstract class Entity<
.getViewerContext()
.getViewerScopedEntityCompanionForClass(this)
.getQueryContextProvider()
.getRegularEntityQueryContext()
.getQueryContext()
): Promise<boolean> {
const privacyPolicy = new (this.getCompanionDefinition().privacyPolicyClass)();
const evaluationResult = await asyncResult(
@@ -290,7 +290,7 @@ export default abstract class Entity<
.getViewerContext()
.getViewerScopedEntityCompanionForClass(this)
.getQueryContextProvider()
.getRegularEntityQueryContext()
.getQueryContext()
): Promise<boolean> {
const privacyPolicy = new (this.getCompanionDefinition().privacyPolicyClass)();
const evaluationResult = await asyncResult(
+37 -12
View File
@@ -23,6 +23,7 @@ export default class EntityAssociationLoader<
* @param queryContext - query context in which to perform the load
*/
async loadAssociatedEntityAsync<
TIdentifyingField extends keyof Pick<TFields, TSelectedFields>,
TAssociatedFields,
TAssociatedID,
TAssociatedEntity extends ReadonlyEntity<
@@ -40,7 +41,7 @@ export default class EntityAssociationLoader<
>,
TAssociatedSelectedFields extends keyof TAssociatedFields = keyof TAssociatedFields
>(
fieldIdentifyingAssociatedEntity: keyof Pick<TFields, TSelectedFields>,
fieldIdentifyingAssociatedEntity: TIdentifyingField,
associatedEntityClass: IEntityClass<
TAssociatedFields,
TAssociatedID,
@@ -53,15 +54,26 @@ export default class EntityAssociationLoader<
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
.getQueryContextProvider()
.getRegularEntityQueryContext()
): Promise<Result<TAssociatedEntity>> {
.getQueryContext()
): Promise<
Result<null extends TFields[TIdentifyingField] ? TAssociatedEntity | null : TAssociatedEntity>
> {
const associatedEntityID = this.entity.getField(fieldIdentifyingAssociatedEntity);
if (!associatedEntityID) {
return result(null) as Result<
null extends TFields[TIdentifyingField] ? TAssociatedEntity | null : TAssociatedEntity
>;
}
const loader = this.entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
.getLoaderFactory()
.forLoad(queryContext);
return await loader.loadByIDAsync((associatedEntityID as unknown) as TAssociatedID);
return (await loader.loadByIDAsync((associatedEntityID as unknown) as TAssociatedID)) as Result<
null extends TFields[TIdentifyingField] ? TAssociatedEntity | null : TAssociatedEntity
>;
}
/**
@@ -99,12 +111,12 @@ export default class EntityAssociationLoader<
TAssociatedPrivacyPolicy,
TAssociatedSelectedFields
>,
associatedEntityFieldContainingThisID: keyof TAssociatedFields,
associatedEntityFieldContainingThisID: keyof Pick<TAssociatedFields, TAssociatedSelectedFields>,
queryContext: EntityQueryContext = this.entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
.getQueryContextProvider()
.getRegularEntityQueryContext()
.getQueryContext()
): Promise<readonly Result<TAssociatedEntity>[]> {
const thisID = this.entity.getID();
const loader = this.entity
@@ -153,14 +165,17 @@ export default class EntityAssociationLoader<
TAssociatedPrivacyPolicy,
TAssociatedSelectedFields
>,
associatedEntityLookupByField: keyof TAssociatedFields,
associatedEntityLookupByField: keyof Pick<TAssociatedFields, TAssociatedSelectedFields>,
queryContext: EntityQueryContext = this.entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
.getQueryContextProvider()
.getRegularEntityQueryContext()
.getQueryContext()
): Promise<Result<TAssociatedEntity> | null> {
const associatedFieldValue = this.entity.getField(fieldIdentifyingAssociatedEntity);
if (!associatedFieldValue) {
return null;
}
const loader = this.entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
@@ -207,14 +222,18 @@ export default class EntityAssociationLoader<
TAssociatedPrivacyPolicy,
TAssociatedSelectedFields
>,
associatedEntityLookupByField: keyof TAssociatedFields,
associatedEntityLookupByField: keyof Pick<TAssociatedFields, TAssociatedSelectedFields>,
queryContext: EntityQueryContext = this.entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
.getQueryContextProvider()
.getRegularEntityQueryContext()
.getQueryContext()
): Promise<readonly Result<TAssociatedEntity>[]> {
const associatedFieldValue = this.entity.getField(fieldIdentifyingAssociatedEntity);
if (!associatedFieldValue) {
return [];
}
const loader = this.entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
@@ -424,13 +443,19 @@ export default class EntityAssociationLoader<
queryContext
);
} else {
associatedEntityResult = await currentEntity
const associatedEntityResultLocal = await currentEntity
.associationLoader()
.loadAssociatedEntityAsync(
fieldIdentifyingAssociatedEntity,
associatedEntityClass,
queryContext
);
if (associatedEntityResultLocal.ok && associatedEntityResultLocal.value === null) {
associatedEntityResult = null;
} else {
associatedEntityResult = associatedEntityResultLocal;
}
}
if (!associatedEntityResult) {
@@ -491,5 +516,5 @@ export interface EntityLoadThroughDirective<
* Field by which to load the instance of associatedEntityClass. If not provided, the
* associatedEntityClass instance is fetched by its ID.
*/
associatedEntityLookupByField?: keyof TAssociatedFields;
associatedEntityLookupByField?: keyof Pick<TAssociatedFields, TAssociatedSelectedFields>;
}
+30 -5
View File
@@ -1,8 +1,10 @@
import { IEntityClass } from './Entity';
import EntityLoaderFactory from './EntityLoaderFactory';
import EntityMutationTriggerConfiguration from './EntityMutationTriggerConfiguration';
import EntityMutationValidator from './EntityMutationValidator';
import EntityMutatorFactory from './EntityMutatorFactory';
import EntityPrivacyPolicy from './EntityPrivacyPolicy';
import IEntityQueryContextProvider from './IEntityQueryContextProvider';
import EntityQueryContextProvider from './EntityQueryContextProvider';
import ReadonlyEntity from './ReadonlyEntity';
import ViewerContext from './ViewerContext';
import EntityTableDataCoordinator from './internal/EntityTableDataCoordinator';
@@ -57,19 +59,42 @@ export default class EntityCompanion<
>,
private readonly tableDataCoordinator: EntityTableDataCoordinator<TFields>,
PrivacyPolicyClass: IPrivacyPolicyClass<TPrivacyPolicy>,
mutationValidators: EntityMutationValidator<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[],
mutationTriggers: EntityMutationTriggerConfiguration<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>,
metricsAdapter: IEntityMetricsAdapter
) {
const privacyPolicy = new PrivacyPolicyClass();
this.entityLoaderFactory = new EntityLoaderFactory(
tableDataCoordinator.entityConfiguration.idField,
this.entityLoaderFactory = new EntityLoaderFactory<
TFields,
TID,
TViewerContext,
TEntity,
TPrivacyPolicy,
TSelectedFields
>(
tableDataCoordinator.entityConfiguration.idField as keyof Pick<TFields, TSelectedFields>,
entityClass,
privacyPolicy,
tableDataCoordinator.dataManager
);
this.entityMutatorFactory = new EntityMutatorFactory(
tableDataCoordinator.entityConfiguration.idField,
tableDataCoordinator.entityConfiguration,
entityClass,
privacyPolicy,
mutationValidators,
mutationTriggers,
this.entityLoaderFactory,
tableDataCoordinator.databaseAdapter,
metricsAdapter
@@ -101,7 +126,7 @@ export default class EntityCompanion<
/**
* Get the query context provider for this entity.
*/
getQueryContextProvider(): IEntityQueryContextProvider {
getQueryContextProvider(): EntityQueryContextProvider {
return this.tableDataCoordinator.getQueryContextProvider();
}
}
+44 -5
View File
@@ -1,10 +1,12 @@
import { IEntityClass } from './Entity';
import EntityCompanion, { IPrivacyPolicyClass } from './EntityCompanion';
import EntityConfiguration from './EntityConfiguration';
import EntityMutationTriggerConfiguration from './EntityMutationTriggerConfiguration';
import EntityMutationValidator from './EntityMutationValidator';
import EntityPrivacyPolicy from './EntityPrivacyPolicy';
import EntityQueryContextProvider from './EntityQueryContextProvider';
import IEntityCacheAdapterProvider from './IEntityCacheAdapterProvider';
import IEntityDatabaseAdapterProvider from './IEntityDatabaseAdapterProvider';
import IEntityQueryContextProvider from './IEntityQueryContextProvider';
import ReadonlyEntity from './ReadonlyEntity';
import ViewerContext from './ViewerContext';
import EntityTableDataCoordinator from './internal/EntityTableDataCoordinator';
@@ -41,7 +43,7 @@ export enum CacheAdapterFlavor {
*/
export interface DatabaseAdapterFlavorDefinition {
adapterProvider: IEntityDatabaseAdapterProvider;
queryContextProvider: IEntityQueryContextProvider;
queryContextProvider: EntityQueryContextProvider;
}
/**
@@ -80,12 +82,28 @@ export class EntityCompanionDefinition<
>;
readonly entityConfiguration: EntityConfiguration<TFields>;
readonly privacyPolicyClass: IPrivacyPolicyClass<TPrivacyPolicy>;
readonly mutationValidators: EntityMutationValidator<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[];
readonly mutationTriggers: EntityMutationTriggerConfiguration<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>;
readonly entitySelectedFields: TSelectedFields[];
constructor({
entityClass,
entityConfiguration,
privacyPolicyClass,
mutationValidators = [],
mutationTriggers = {},
entitySelectedFields = Array.from(entityConfiguration.schema.keys()) as TSelectedFields[],
}: {
entityClass: IEntityClass<
@@ -98,11 +116,27 @@ export class EntityCompanionDefinition<
>;
entityConfiguration: EntityConfiguration<TFields>;
privacyPolicyClass: IPrivacyPolicyClass<TPrivacyPolicy>;
mutationValidators?: EntityMutationValidator<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[];
mutationTriggers?: EntityMutationTriggerConfiguration<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>;
entitySelectedFields?: TSelectedFields[];
}) {
this.entityClass = entityClass;
this.entityConfiguration = entityConfiguration;
this.privacyPolicyClass = privacyPolicyClass;
this.mutationValidators = mutationValidators;
this.mutationTriggers = mutationTriggers;
this.entitySelectedFields = entitySelectedFields;
}
}
@@ -177,20 +211,24 @@ export default class EntityCompanionProvider {
>
): EntityCompanion<TFields, TID, TViewerContext, TEntity, TPrivacyPolicy, TSelectedFields> {
const tableDataCoordinator = this.getTableDataCoordinatorForEntity(
entityCompanionDefinition.entityConfiguration
entityCompanionDefinition.entityConfiguration,
entityClass.name
);
return computeIfAbsent(this.companionMap, entityClass.name, () => {
return new EntityCompanion(
entityCompanionDefinition.entityClass,
tableDataCoordinator,
entityCompanionDefinition.privacyPolicyClass,
entityCompanionDefinition.mutationValidators,
entityCompanionDefinition.mutationTriggers,
this.metricsAdapter
);
});
}
private getTableDataCoordinatorForEntity<TFields>(
entityConfiguration: EntityConfiguration<TFields>
entityConfiguration: EntityConfiguration<TFields>,
entityClassName: string
): EntityTableDataCoordinator<TFields> {
return computeIfAbsent(this.tableDataCoordinatorMap, entityConfiguration.tableName, () => {
const entityDatabaseAdapterFlavor = this.databaseAdapterFlavors[
@@ -204,7 +242,8 @@ export default class EntityCompanionProvider {
entityDatabaseAdapterFlavor.adapterProvider,
entityCacheAdapterFlavor.cacheAdapterProvider,
entityDatabaseAdapterFlavor.queryContextProvider,
this.metricsAdapter
this.metricsAdapter,
entityClassName
);
});
}
@@ -1,3 +1,4 @@
import { IEntityClass } from './Entity';
import { DatabaseAdapterFlavor, CacheAdapterFlavor } from './EntityCompanionProvider';
import { EntityFieldDefinition } from './EntityFields';
import { mapMap, invertMap, reduceMap } from './utils/collections/maps';
@@ -12,6 +13,7 @@ export default class EntityConfiguration<TFields> {
readonly cacheableKeys: ReadonlySet<keyof TFields>;
readonly cacheKeyVersion: number;
readonly getInboundEdges: () => IEntityClass<any, any, any, any, any, any>[];
readonly schema: ReadonlyMap<keyof TFields, EntityFieldDefinition>;
readonly entityToDBFieldsKeyMapping: ReadonlyMap<keyof TFields, string>;
readonly dbToEntityFieldsKeyMapping: ReadonlyMap<string, keyof TFields>;
@@ -23,6 +25,7 @@ export default class EntityConfiguration<TFields> {
idField,
tableName,
schema,
getInboundEdges = () => [],
cacheKeyVersion = 0,
databaseAdapterFlavor,
cacheAdapterFlavor,
@@ -30,6 +33,7 @@ export default class EntityConfiguration<TFields> {
idField: keyof TFields;
tableName: string;
schema: Record<keyof TFields, EntityFieldDefinition>;
getInboundEdges?: () => IEntityClass<any, any, any, any, any, any>[];
cacheKeyVersion?: number;
databaseAdapterFlavor: DatabaseAdapterFlavor;
cacheAdapterFlavor: CacheAdapterFlavor;
@@ -40,6 +44,8 @@ export default class EntityConfiguration<TFields> {
this.databaseAdapterFlavor = databaseAdapterFlavor;
this.cacheAdapterFlavor = cacheAdapterFlavor;
this.getInboundEdges = getInboundEdges;
// external schema is a Record to typecheck that all fields have FieldDefinitions,
// but internally the most useful representation is a map for lookups
// TODO(wschurman): validate schema
@@ -348,10 +348,6 @@ export default abstract class EntityDatabaseAdapter<TFields> {
throw new Error(
`Excessive deletions from database adapter delete: ${this.entityConfiguration.tableName}(id = ${id})`
);
} else if (numDeleted === 0) {
throw new Error(
`No deletions from database adapter delete: ${this.entityConfiguration.tableName}(id = ${id})`
);
}
}
+96 -1
View File
@@ -1,6 +1,92 @@
import { IEntityClass } from './Entity';
import EntityPrivacyPolicy from './EntityPrivacyPolicy';
import ReadonlyEntity from './ReadonlyEntity';
import ViewerContext from './ViewerContext';
export enum EntityEdgeDeletionBehavior {
/**
* Default. Invalidate the cache for all entities that reference the entity
* being deleted through this field, and transitively run deletions on those entities.
* This is most useful when the database itself expresses foreign
* keys and cascading deletes or set nulls and the entity framework just needs to
* be kept consistent with the state of the database.
*/
CASCADE_DELETE_INVALIDATE_CACHE,
/**
* Delete all entities that reference the entity being deleted through this field. This is very similar
* to SQL `ON DELETE CASCADE` but is done in the Entity framework instead of at the underlying level.
* This will also invalidate the cached referencing entities.
*/
CASCADE_DELETE,
/**
* Set this field to null when the referenced entity is deleted. This is very similar
* to SQL `ON DELETE SET NULL` but is done in the Entity framework instead of at the underlying level.
* This will also invalidate the cached referencing entities.
*/
SET_NULL,
}
export interface EntityAssociationDefinition<
TViewerContext extends ViewerContext,
TAssociatedFields,
TAssociatedID,
TAssociatedEntity extends ReadonlyEntity<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedSelectedFields
>,
TAssociatedPrivacyPolicy extends EntityPrivacyPolicy<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedEntity,
TAssociatedSelectedFields
>,
TAssociatedSelectedFields extends keyof TAssociatedFields = keyof TAssociatedFields
> {
/**
* Class of entity on the other end of this edge.
*/
getAssociatedEntityClass: () => IEntityClass<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedEntity,
TAssociatedPrivacyPolicy,
TAssociatedSelectedFields
>;
/**
* Field by which to load the instance of associatedEntityClass. If not provided, the
* associatedEntityClass instance is fetched by its ID.
*/
associatedEntityLookupByField?: keyof TAssociatedFields;
/**
* What action to perform on the current entity when the entity on the referencing end of
* this edge is deleted.
*
* @remarks
* The entity framework doesn't prescribe a one-size-fits-all solution for referential
* integrity; instead it exposes mechanisms that supports both database foreign key constraints
* and implicit entity-specified foreign keys. Choosing which approach to use often depends on
* application requirements, and sometimes even a mix-and-match is the right choice.
*
* - If referential integrity is critical to your application, database foreign key constraints
* combined with {@link EntityEdgeDeletionBehavior.CASACDE_DELETE_INVALIDATE_CACHE} are recommended.
* - If the database being used doesn't support foreign keys, then using the entity framework for referential
* integrity is recommended.
*/
edgeDeletionBehavior?: EntityEdgeDeletionBehavior;
}
export abstract class EntityFieldDefinition {
readonly columnName: string;
readonly cache: boolean;
readonly association?: EntityAssociationDefinition<any, any, any, any, any, any>;
/**
*
* @param columnName - Column name in the database.
@@ -8,9 +94,18 @@ export abstract class EntityFieldDefinition {
* used to derive a cache key for the cache entry. If true, this column must be able uniquely
* identify the entity.
*/
constructor({ columnName, cache = false }: { columnName: string; cache?: boolean }) {
constructor({
columnName,
cache = false,
association,
}: {
columnName: string;
cache?: boolean;
association?: EntityAssociationDefinition<any, any, any, any, any, any>;
}) {
this.columnName = columnName;
this.cache = cache;
this.association = association;
}
}
+87 -40
View File
@@ -33,7 +33,7 @@ export default class EntityLoader<
constructor(
private readonly viewerContext: TViewerContext,
private readonly queryContext: EntityQueryContext,
private readonly idField: keyof TFields,
private readonly idField: keyof Pick<TFields, TSelectedFields>,
private readonly entityClass: IEntityClass<
TFields,
TID,
@@ -69,30 +69,38 @@ export default class EntityLoader<
* @returns map from fieldValue to entity results that match the query for that fieldValue,
* where result errors can be UnauthorizedError
*/
async loadManyByFieldEqualingManyAsync<N extends keyof TFields>(
async loadManyByFieldEqualingManyAsync<N extends keyof Pick<TFields, TSelectedFields>>(
fieldName: N,
fieldValues: readonly NonNullable<TFields[N]>[]
): Promise<ReadonlyMap<NonNullable<TFields[N]>, readonly Result<TEntity>[]>> {
const fieldValuesToObjects = await this.dataManager.loadManyByFieldEqualingAsync(
const fieldValuesToFieldObjects = await this.dataManager.loadManyByFieldEqualingAsync(
this.queryContext,
fieldName,
fieldValues
);
const fieldValuesToUncheckedEntities = mapMap(fieldValuesToObjects, (v) => {
return v.map((obj) => {
return new this.entityClass(this.viewerContext, obj);
});
});
const fieldValuesToUncheckedEntityResults = mapMap(fieldValuesToFieldObjects, (fieldObjects) =>
this.tryConstructEntities(fieldObjects)
);
return await mapMapAsync(fieldValuesToUncheckedEntities, async (v) => {
return await Promise.all(
v.map((entity) =>
asyncResult(
this.privacyPolicy.authorizeReadAsync(this.viewerContext, this.queryContext, entity)
)
)
);
});
return await mapMapAsync(
fieldValuesToUncheckedEntityResults,
async (uncheckedEntityResults) => {
return await Promise.all(
uncheckedEntityResults.map(async (uncheckedEntityResult) => {
if (!uncheckedEntityResult.ok) {
return uncheckedEntityResult;
}
return await asyncResult(
this.privacyPolicy.authorizeReadAsync(
this.viewerContext,
this.queryContext,
uncheckedEntityResult.value
)
);
})
);
}
);
}
/**
@@ -101,7 +109,7 @@ export default class EntityLoader<
* @param fieldValue - fieldName field value being queried
* @returns array of entity results that match the query for fieldValue, where result error can be UnauthorizedError
*/
async loadManyByFieldEqualingAsync<N extends keyof TFields>(
async loadManyByFieldEqualingAsync<N extends keyof Pick<TFields, TSelectedFields>>(
fieldName: N,
fieldValue: NonNullable<TFields[N]>
): Promise<readonly Result<TEntity>[]> {
@@ -121,7 +129,7 @@ export default class EntityLoader<
* @returns entity result where uniqueFieldName equals fieldValue, or null if no entity matches the condition.
* @throws when multiple entities match the condition
*/
async loadByFieldEqualingAsync<N extends keyof TFields>(
async loadByFieldEqualingAsync<N extends keyof Pick<TFields, TSelectedFields>>(
uniqueFieldName: N,
fieldValue: NonNullable<TFields[N]>
): Promise<Result<TEntity> | null> {
@@ -189,25 +197,29 @@ export default class EntityLoader<
* @param querySelectionModifiers - limit, offset, and orderBy for the query
* @returns array of entity results that match the query, where result error can be UnauthorizedError
*/
async loadManyByFieldEqualityConjunctionAsync<N extends keyof TFields>(
async loadManyByFieldEqualityConjunctionAsync<N extends keyof Pick<TFields, TSelectedFields>>(
fieldEqualityOperands: FieldEqualityCondition<TFields, N>[],
querySelectionModifiers: QuerySelectionModifiers<TFields> = {}
): Promise<readonly Result<TEntity>[]> {
const fieldValuesArray = await this.dataManager.loadManyByFieldEqualityConjunctionAsync(
const fieldObjects = await this.dataManager.loadManyByFieldEqualityConjunctionAsync(
this.queryContext,
fieldEqualityOperands,
querySelectionModifiers
);
const uncheckedEntities = fieldValuesArray.map((obj) => {
return new this.entityClass(this.viewerContext, obj);
});
const uncheckedEntityResults = this.tryConstructEntities(fieldObjects);
return await Promise.all(
uncheckedEntities.map(async (entity) =>
asyncResult(
this.privacyPolicy.authorizeReadAsync(this.viewerContext, this.queryContext, entity)
)
)
uncheckedEntityResults.map(async (uncheckedEntityResult) => {
if (!uncheckedEntityResult.ok) {
return uncheckedEntityResult;
}
return await asyncResult(
this.privacyPolicy.authorizeReadAsync(
this.viewerContext,
this.queryContext,
uncheckedEntityResult.value
)
);
})
);
}
@@ -241,22 +253,26 @@ export default class EntityLoader<
bindings: any[] | object,
querySelectionModifiers: QuerySelectionModifiers<TFields> = {}
): Promise<readonly Result<TEntity>[]> {
const fieldValuesArray = await this.dataManager.loadManyByRawWhereClauseAsync(
const fieldObjects = await this.dataManager.loadManyByRawWhereClauseAsync(
this.queryContext,
rawWhereClause,
bindings,
querySelectionModifiers
);
const uncheckedEntities = fieldValuesArray.map((obj) => {
return new this.entityClass(this.viewerContext, obj);
});
const uncheckedEntityResults = this.tryConstructEntities(fieldObjects);
return await Promise.all(
uncheckedEntities.map(async (entity) =>
asyncResult(
this.privacyPolicy.authorizeReadAsync(this.viewerContext, this.queryContext, entity)
)
)
uncheckedEntityResults.map(async (uncheckedEntityResult) => {
if (!uncheckedEntityResult.ok) {
return uncheckedEntityResult;
}
return await asyncResult(
this.privacyPolicy.authorizeReadAsync(
this.viewerContext,
this.queryContext,
uncheckedEntityResult.value
)
);
})
);
}
@@ -267,4 +283,35 @@ export default class EntityLoader<
async invalidateFieldsAsync(objectFields: Readonly<TFields>): Promise<void> {
await this.dataManager.invalidateObjectFieldsAsync(objectFields);
}
async invalidateFieldsTransactionalAsync(objectFields: Readonly<TFields>): Promise<void> {
await this.dataManager.invalidateObjectFieldsTransactionalAsync(
this.queryContext,
objectFields
);
}
/**
* Invalidate all caches for an entity. One potential use case would be to keep the entity
* framework in sync with changes made to data outside of the framework.
* @param entity - entity to be invalidated
*/
async invalidateEntityAsync(entity: TEntity): Promise<void> {
await this.invalidateFieldsAsync(entity.getAllDatabaseFields());
}
/**
* Wrap entity construction in try/catch and return Results. Used to prevent constructor errors
* thrown for one entity instantiation from interfering with other entity instantiatons of the same query.
* @param fieldsObjects - array of entity data objects to construct entities
*/
private tryConstructEntities(fieldsObjects: readonly TFields[]): readonly Result<TEntity>[] {
return fieldsObjects.map((fieldsObject) => {
try {
return result(new this.entityClass(this.viewerContext, fieldsObject));
} catch (e) {
return result(e);
}
});
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ export default class EntityLoaderFactory<
TSelectedFields extends keyof TFields
> {
constructor(
private readonly idField: keyof TFields,
private readonly idField: keyof Pick<TFields, TSelectedFields>,
private readonly entityClass: IEntityClass<
TFields,
TID,
@@ -0,0 +1,97 @@
import { EntityQueryContext } from './EntityQueryContext';
import ReadonlyEntity from './ReadonlyEntity';
import ViewerContext from './ViewerContext';
/**
* Interface to define trigger behavior for entities.
*/
export default interface EntityMutationTriggerConfiguration<
TFields,
TID,
TViewerContext extends ViewerContext,
TEntity extends ReadonlyEntity<TFields, TID, TViewerContext, TSelectedFields>,
TSelectedFields extends keyof TFields = keyof TFields
> {
/**
* Trigger set that runs within the transaction but before the entity is created in the database.
*/
beforeCreate?: EntityMutationTrigger<TFields, TID, TViewerContext, TEntity, TSelectedFields>[];
/**
* Trigger set that runs within the transaction but after the entity is created in the database and cache is invalidated.
*/
afterCreate?: EntityMutationTrigger<TFields, TID, TViewerContext, TEntity, TSelectedFields>[];
/**
* Trigger set that runs within the transaction but before the entity is updated in the database.
*/
beforeUpdate?: EntityMutationTrigger<TFields, TID, TViewerContext, TEntity, TSelectedFields>[];
/**
* Trigger set that runs within the transaction but after the entity is updated in the database and cache is invalidated.
*/
afterUpdate?: EntityMutationTrigger<TFields, TID, TViewerContext, TEntity, TSelectedFields>[];
/**
* Trigger set that runs within the transaction but before the entity is deleted from the database.
*/
beforeDelete?: EntityMutationTrigger<TFields, TID, TViewerContext, TEntity, TSelectedFields>[];
/**
* Trigger set that runs within the transaction but after the entity is deleted from the database and cache is invalidated.
*/
afterDelete?: EntityMutationTrigger<TFields, TID, TViewerContext, TEntity, TSelectedFields>[];
/**
* Trigger set that runs within the transaction but before the entity is created, updated, or deleted.
*/
beforeAll?: EntityMutationTrigger<TFields, TID, TViewerContext, TEntity, TSelectedFields>[];
/**
* Trigger set that runs within the transaction but before the entity is created in, updated in, or deleted from
* the database and the cache is invalidated.
*/
afterAll?: EntityMutationTrigger<TFields, TID, TViewerContext, TEntity, TSelectedFields>[];
/**
* Trigger set that runs after committing the transaction unless one is supplied
* after any mutation (create, update, delete). If the call to the mutation is wrapped in a transaction,
* this too will be within the transaction.
*/
afterCommit?: EntityNonTransactionalMutationTrigger<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[];
}
/**
* A trigger is a way to specify entity mutation operation side-effects that run within the
* same transaction as the mutation itself. The one exception is afterCommit, which will run within
* the transaction if a transaction is supplied.
*/
export abstract class EntityMutationTrigger<
TFields,
TID,
TViewerContext extends ViewerContext,
TEntity extends ReadonlyEntity<TFields, TID, TViewerContext, TSelectedFields>,
TSelectedFields extends keyof TFields = keyof TFields
> {
abstract async executeAsync(
viewerContext: TViewerContext,
queryContext: EntityQueryContext,
entity: TEntity
): Promise<void>;
}
/**
* A non-transactional trigger is like a {@link EntityMutationTrigger} but used for afterCommit triggers
* since they explicitly occur outside of the transaction.
*/
export abstract class EntityNonTransactionalMutationTrigger<
TFields,
TID,
TViewerContext extends ViewerContext,
TEntity extends ReadonlyEntity<TFields, TID, TViewerContext, TSelectedFields>,
TSelectedFields extends keyof TFields = keyof TFields
> {
abstract async executeAsync(viewerContext: TViewerContext, entity: TEntity): Promise<void>;
}
@@ -0,0 +1,21 @@
import { EntityQueryContext } from './EntityQueryContext';
import ReadonlyEntity from './ReadonlyEntity';
import ViewerContext from './ViewerContext';
/*
* A validator is a way to specify entity mutation validation that runs within the
* same transaction as the mutation itself before creating or updating an entity.
*/
export default abstract class EntityMutationValidator<
TFields,
TID,
TViewerContext extends ViewerContext,
TEntity extends ReadonlyEntity<TFields, TID, TViewerContext, TSelectedFields>,
TSelectedFields extends keyof TFields = keyof TFields
> {
abstract async executeAsync(
viewerContext: TViewerContext,
queryContext: EntityQueryContext,
entity: TEntity
): Promise<void>;
}
+427 -40
View File
@@ -1,14 +1,23 @@
import { Result, asyncResult, result, enforceAsyncResult } from '@expo/results';
import _ from 'lodash';
import Entity, { IEntityClass } from './Entity';
import { EntityCompanionDefinition } from './EntityCompanionProvider';
import EntityConfiguration from './EntityConfiguration';
import EntityDatabaseAdapter from './EntityDatabaseAdapter';
import { EntityEdgeDeletionBehavior } from './EntityFields';
import EntityLoaderFactory from './EntityLoaderFactory';
import EntityMutationTriggerConfiguration, {
EntityMutationTrigger,
EntityNonTransactionalMutationTrigger,
} from './EntityMutationTriggerConfiguration';
import EntityMutationValidator from './EntityMutationValidator';
import EntityPrivacyPolicy from './EntityPrivacyPolicy';
import { EntityQueryContext } from './EntityQueryContext';
import { EntityQueryContext, EntityTransactionalQueryContext } from './EntityQueryContext';
import ReadonlyEntity from './ReadonlyEntity';
import ViewerContext from './ViewerContext';
import { timeAndLogMutationEventAsync } from './metrics/EntityMetricsUtils';
import IEntityMetricsAdapter, { EntityMetricsMutationType } from './metrics/IEntityMetricsAdapter';
import { mapMapAsync } from './utils/collections/maps';
abstract class BaseMutator<
TFields,
@@ -27,7 +36,7 @@ abstract class BaseMutator<
constructor(
protected readonly viewerContext: TViewerContext,
protected readonly queryContext: EntityQueryContext,
protected readonly idField: keyof TFields,
protected readonly entityConfiguration: EntityConfiguration<TFields>,
protected readonly entityClass: IEntityClass<
TFields,
TID,
@@ -37,6 +46,20 @@ abstract class BaseMutator<
TSelectedFields
>,
protected readonly privacyPolicy: TPrivacyPolicy,
protected readonly mutationValidators: EntityMutationValidator<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[],
protected readonly mutationTriggers: EntityMutationTriggerConfiguration<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>,
protected readonly entityLoaderFactory: EntityLoaderFactory<
TFields,
TID,
@@ -48,6 +71,42 @@ abstract class BaseMutator<
protected readonly databaseAdapter: EntityDatabaseAdapter<TFields>,
protected readonly metricsAdapter: IEntityMetricsAdapter
) {}
protected async executeMutationTriggersOrValidatorsAsync(
triggersOrValidators:
| EntityMutationTrigger<TFields, TID, TViewerContext, TEntity, TSelectedFields>[]
| EntityMutationValidator<TFields, TID, TViewerContext, TEntity, TSelectedFields>[]
| undefined,
queryContext: EntityQueryContext,
entity: TEntity
): Promise<void> {
if (!triggersOrValidators) {
return;
}
await Promise.all(
triggersOrValidators.map((triggerOrValidator) =>
triggerOrValidator.executeAsync(this.viewerContext, queryContext, entity)
)
);
}
protected async executeNonTransactionalMutationTriggersOrValidatorsAsync(
triggers:
| EntityNonTransactionalMutationTrigger<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[]
| undefined,
entity: TEntity
): Promise<void> {
if (!triggers) {
return;
}
await Promise.all(triggers.map((trigger) => trigger.executeAsync(this.viewerContext, entity)));
}
}
/**
@@ -74,7 +133,7 @@ export class CreateMutator<
* @param fieldName - entity field being updated
* @param value - value for entity field
*/
setField<K extends keyof TFields>(fieldName: K, value: TFields[K]): this {
setField<K extends keyof Pick<TFields, TSelectedFields>>(fieldName: K, value: TFields[K]): this {
this.fieldsForEntity[fieldName] = value;
return this;
}
@@ -87,8 +146,9 @@ export class CreateMutator<
async createAsync(): Promise<Result<TEntity>> {
return await timeAndLogMutationEventAsync(
this.metricsAdapter,
EntityMetricsMutationType.CREATE
)(this.createInternalAsync());
EntityMetricsMutationType.CREATE,
this.entityClass.name
)(this.createInTransactionAsync());
}
/**
@@ -98,16 +158,24 @@ export class CreateMutator<
return await enforceAsyncResult(this.createAsync());
}
private async createInternalAsync(): Promise<Result<TEntity>> {
private async createInTransactionAsync(): Promise<Result<TEntity>> {
return await this.queryContext.runInTransactionIfNotInTransactionAsync((innerQueryContext) =>
this.createInternalAsync(innerQueryContext)
);
}
private async createInternalAsync(
queryContext: EntityTransactionalQueryContext
): Promise<Result<TEntity>> {
const temporaryEntityForPrivacyCheck = new this.entityClass(this.viewerContext, ({
[this.idField]: '00000000-0000-0000-0000-000000000000', // zero UUID
[this.entityConfiguration.idField]: '00000000-0000-0000-0000-000000000000', // zero UUID
...this.fieldsForEntity,
} as unknown) as TFields);
const authorizeCreateResult = await asyncResult(
this.privacyPolicy.authorizeCreateAsync(
this.viewerContext,
this.queryContext,
queryContext,
temporaryEntityForPrivacyCheck
)
);
@@ -115,16 +183,55 @@ export class CreateMutator<
return authorizeCreateResult;
}
const insertResult = await this.databaseAdapter.insertAsync(
this.queryContext,
this.fieldsForEntity
await this.executeMutationTriggersOrValidatorsAsync(
this.mutationValidators,
queryContext,
temporaryEntityForPrivacyCheck
);
await this.executeMutationTriggersOrValidatorsAsync(
this.mutationTriggers.beforeAll,
queryContext,
temporaryEntityForPrivacyCheck
);
await this.executeMutationTriggersOrValidatorsAsync(
this.mutationTriggers.beforeCreate,
queryContext,
temporaryEntityForPrivacyCheck
);
const entityLoader = this.entityLoaderFactory.forLoad(this.viewerContext, this.queryContext);
await entityLoader.invalidateFieldsAsync(insertResult);
const insertResult = await this.databaseAdapter.insertAsync(queryContext, this.fieldsForEntity);
const entityLoader = this.entityLoaderFactory.forLoad(this.viewerContext, queryContext);
queryContext.appendPostCommitCallback(
entityLoader.invalidateFieldsAsync.bind(entityLoader, insertResult)
);
await entityLoader.invalidateFieldsTransactionalAsync(insertResult);
const unauthorizedEntityAfterInsert = new this.entityClass(this.viewerContext, insertResult);
return await entityLoader.loadByIDAsync(unauthorizedEntityAfterInsert.getID());
const newEntity = await entityLoader
.enforcing()
.loadByIDAsync(unauthorizedEntityAfterInsert.getID());
await this.executeMutationTriggersOrValidatorsAsync(
this.mutationTriggers.afterCreate,
queryContext,
newEntity
);
await this.executeMutationTriggersOrValidatorsAsync(
this.mutationTriggers.afterAll,
queryContext,
newEntity
);
queryContext.appendPostCommitCallback(
this.executeNonTransactionalMutationTriggersOrValidatorsAsync.bind(
this,
this.mutationTriggers.afterCommit,
newEntity
)
);
return result(newEntity);
}
}
@@ -152,7 +259,7 @@ export class UpdateMutator<
constructor(
viewerContext: TViewerContext,
queryContext: EntityQueryContext,
idField: keyof TFields,
entityConfiguration: EntityConfiguration<TFields>,
entityClass: IEntityClass<
TFields,
TID,
@@ -162,6 +269,20 @@ export class UpdateMutator<
TSelectedFields
>,
privacyPolicy: TPrivacyPolicy,
mutationValidators: EntityMutationValidator<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[],
mutationTriggers: EntityMutationTriggerConfiguration<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>,
entityLoaderFactory: EntityLoaderFactory<
TFields,
TID,
@@ -177,15 +298,17 @@ export class UpdateMutator<
super(
viewerContext,
queryContext,
idField,
entityConfiguration,
entityClass,
privacyPolicy,
mutationValidators,
mutationTriggers,
entityLoaderFactory,
databaseAdapter,
metricsAdapter
);
this.originalFieldsForEntity = _.cloneDeep(fieldsForEntity);
this.fieldsForEntity = _.cloneDeep(fieldsForEntity);
this.originalFieldsForEntity = { ...fieldsForEntity };
this.fieldsForEntity = { ...fieldsForEntity };
}
/**
@@ -193,7 +316,7 @@ export class UpdateMutator<
* @param fieldName - entity field being updated
* @param value - value for entity field
*/
setField<K extends keyof TFields>(fieldName: K, value: TFields[K]): this {
setField<K extends keyof Pick<TFields, TSelectedFields>>(fieldName: K, value: TFields[K]): this {
this.fieldsForEntity[fieldName] = value;
this.updatedFields[fieldName] = value;
return this;
@@ -208,8 +331,9 @@ export class UpdateMutator<
async updateAsync(): Promise<Result<TEntity>> {
return await timeAndLogMutationEventAsync(
this.metricsAdapter,
EntityMetricsMutationType.UPDATE
)(this.updateInternalAsync());
EntityMetricsMutationType.UPDATE,
this.entityClass.name
)(this.updateInTransactionAsync());
}
/**
@@ -219,12 +343,20 @@ export class UpdateMutator<
return await enforceAsyncResult(this.updateAsync());
}
private async updateInternalAsync(): Promise<Result<TEntity>> {
private async updateInTransactionAsync(): Promise<Result<TEntity>> {
return await this.queryContext.runInTransactionIfNotInTransactionAsync((innerQueryContext) =>
this.updateInternalAsync(innerQueryContext)
);
}
private async updateInternalAsync(
queryContext: EntityTransactionalQueryContext
): Promise<Result<TEntity>> {
const entityAboutToBeUpdated = new this.entityClass(this.viewerContext, this.fieldsForEntity);
const authorizeUpdateResult = await asyncResult(
this.privacyPolicy.authorizeUpdateAsync(
this.viewerContext,
this.queryContext,
queryContext,
entityAboutToBeUpdated
)
);
@@ -232,20 +364,68 @@ export class UpdateMutator<
return authorizeUpdateResult;
}
await this.executeMutationTriggersOrValidatorsAsync(
this.mutationValidators,
queryContext,
entityAboutToBeUpdated
);
await this.executeMutationTriggersOrValidatorsAsync(
this.mutationTriggers.beforeAll,
queryContext,
entityAboutToBeUpdated
);
await this.executeMutationTriggersOrValidatorsAsync(
this.mutationTriggers.beforeUpdate,
queryContext,
entityAboutToBeUpdated
);
const updateResult = await this.databaseAdapter.updateAsync(
this.queryContext,
this.idField,
queryContext,
this.entityConfiguration.idField,
entityAboutToBeUpdated.getID(),
this.updatedFields
);
const entityLoader = this.entityLoaderFactory.forLoad(this.viewerContext, this.queryContext);
const entityLoader = this.entityLoaderFactory.forLoad(this.viewerContext, queryContext);
await entityLoader.invalidateFieldsAsync(this.originalFieldsForEntity);
await entityLoader.invalidateFieldsAsync(this.fieldsForEntity);
queryContext.appendPostCommitCallback(
entityLoader.invalidateFieldsAsync.bind(entityLoader, this.originalFieldsForEntity)
);
queryContext.appendPostCommitCallback(
entityLoader.invalidateFieldsAsync.bind(entityLoader, this.fieldsForEntity)
);
await Promise.all([
entityLoader.invalidateFieldsTransactionalAsync(this.originalFieldsForEntity),
entityLoader.invalidateFieldsTransactionalAsync(this.fieldsForEntity),
]);
const unauthorizedEntityAfterUpdate = new this.entityClass(this.viewerContext, updateResult);
return await entityLoader.loadByIDAsync(unauthorizedEntityAfterUpdate.getID());
const updatedEntity = await entityLoader
.enforcing()
.loadByIDAsync(unauthorizedEntityAfterUpdate.getID());
await this.executeMutationTriggersOrValidatorsAsync(
this.mutationTriggers.afterUpdate,
queryContext,
updatedEntity
);
await this.executeMutationTriggersOrValidatorsAsync(
this.mutationTriggers.afterAll,
queryContext,
updatedEntity
);
queryContext.appendPostCommitCallback(
this.executeNonTransactionalMutationTriggersOrValidatorsAsync.bind(
this,
this.mutationTriggers.afterCommit,
updatedEntity
)
);
return result(updatedEntity);
}
}
@@ -269,7 +449,7 @@ export class DeleteMutator<
constructor(
viewerContext: TViewerContext,
queryContext: EntityQueryContext,
idField: keyof TFields,
entityConfiguration: EntityConfiguration<TFields>,
entityClass: IEntityClass<
TFields,
TID,
@@ -279,6 +459,20 @@ export class DeleteMutator<
TSelectedFields
>,
privacyPolicy: TPrivacyPolicy,
mutationValidators: EntityMutationValidator<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[],
mutationTriggers: EntityMutationTriggerConfiguration<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>,
entityLoaderFactory: EntityLoaderFactory<
TFields,
TID,
@@ -294,9 +488,11 @@ export class DeleteMutator<
super(
viewerContext,
queryContext,
idField,
entityConfiguration,
entityClass,
privacyPolicy,
mutationValidators,
mutationTriggers,
entityLoaderFactory,
databaseAdapter,
metricsAdapter
@@ -310,8 +506,9 @@ export class DeleteMutator<
async deleteAsync(): Promise<Result<void>> {
return await timeAndLogMutationEventAsync(
this.metricsAdapter,
EntityMetricsMutationType.DELETE
)(this.deleteInternalAsync());
EntityMetricsMutationType.DELETE,
this.entityClass.name
)(this.deleteInTransactionAsync());
}
/**
@@ -321,21 +518,211 @@ export class DeleteMutator<
return await enforceAsyncResult(this.deleteAsync());
}
private async deleteInternalAsync(): Promise<Result<void>> {
private async deleteInTransactionAsync(
processedEntityIdentifiersFromTransitiveDeletions: Set<string> = new Set(),
skipDatabaseDeletion: boolean = false
): Promise<Result<void>> {
return await this.queryContext.runInTransactionIfNotInTransactionAsync((innerQueryContext) =>
this.deleteInternalAsync(
innerQueryContext,
processedEntityIdentifiersFromTransitiveDeletions,
skipDatabaseDeletion
)
);
}
private async deleteInternalAsync(
queryContext: EntityTransactionalQueryContext,
processedEntityIdentifiersFromTransitiveDeletions: Set<string>,
skipDatabaseDeletion: boolean
): Promise<Result<void>> {
const authorizeDeleteResult = await asyncResult(
this.privacyPolicy.authorizeDeleteAsync(this.viewerContext, this.queryContext, this.entity)
this.privacyPolicy.authorizeDeleteAsync(this.viewerContext, queryContext, this.entity)
);
if (!authorizeDeleteResult.ok) {
return authorizeDeleteResult;
}
const id = this.entity.getID();
await DeleteMutator.processEntityDeletionForInboundEdgesAsync(
this.entity,
queryContext,
processedEntityIdentifiersFromTransitiveDeletions
);
await this.databaseAdapter.deleteAsync(this.queryContext, this.idField, id);
await this.executeMutationTriggersOrValidatorsAsync(
this.mutationTriggers.beforeAll,
queryContext,
this.entity
);
await this.executeMutationTriggersOrValidatorsAsync(
this.mutationTriggers.beforeDelete,
queryContext,
this.entity
);
const entityLoader = this.entityLoaderFactory.forLoad(this.viewerContext, this.queryContext);
await entityLoader.invalidateFieldsAsync(this.entity.getAllDatabaseFields());
if (!skipDatabaseDeletion) {
await this.databaseAdapter.deleteAsync(
queryContext,
this.entityConfiguration.idField,
this.entity.getID()
);
}
const entityLoader = this.entityLoaderFactory.forLoad(this.viewerContext, queryContext);
queryContext.appendPostCommitCallback(
entityLoader.invalidateFieldsAsync.bind(entityLoader, this.entity.getAllDatabaseFields())
);
await entityLoader.invalidateFieldsTransactionalAsync(this.entity.getAllDatabaseFields());
await this.executeMutationTriggersOrValidatorsAsync(
this.mutationTriggers.afterDelete,
queryContext,
this.entity
);
await this.executeMutationTriggersOrValidatorsAsync(
this.mutationTriggers.afterAll,
queryContext,
this.entity
);
queryContext.appendPostCommitCallback(
this.executeNonTransactionalMutationTriggersOrValidatorsAsync.bind(
this,
this.mutationTriggers.afterCommit,
this.entity
)
);
return result();
}
/**
* Finds all entities referencing the specified entity and either deletes them, nullifies
* their references to the specified entity, or invalidates the cache depending on the
* {@link OnDeleteBehavior} of the field referencing the specified entity.
*
* @remarks
* This works by doing reverse fan-out queries:
* 1. Load all entity configurations of entity types that reference this type of entity
* 2. For each entity configuration, find all fields that contain edges to this type of entity
* 3. For each edge field, load all entities with an edge from target entity to this entity via that field
* 4. Perform desired OnDeleteBehavior for entities
*
* @param entity - entity to find all references to
*/
private static async processEntityDeletionForInboundEdgesAsync<
TMFields,
TMID,
TMViewerContext extends ViewerContext,
TMEntity extends Entity<TMFields, TMID, TMViewerContext, TMSelectedFields>,
TMSelectedFields extends keyof TMFields
>(
entity: TMEntity,
queryContext: EntityTransactionalQueryContext,
processedEntityIdentifiers: Set<string>
): Promise<void> {
// prevent infinite reference cycles by keeping track of entities already processed
if (processedEntityIdentifiers.has(entity.getUniqueIdentifier())) {
return;
}
processedEntityIdentifiers.add(entity.getUniqueIdentifier());
const companionDefinition = (entity.constructor as any).getCompanionDefinition() as EntityCompanionDefinition<
TMFields,
TMID,
TMViewerContext,
TMEntity,
EntityPrivacyPolicy<TMFields, TMID, TMViewerContext, TMEntity, TMSelectedFields>,
TMSelectedFields
>;
const entityConfiguration = companionDefinition.entityConfiguration;
const inboundEdges = entityConfiguration.getInboundEdges();
await Promise.all(
inboundEdges.map(async (entityClass) => {
return await mapMapAsync(
entityClass.getCompanionDefinition().entityConfiguration.schema,
async (fieldDefinition, fieldName) => {
const association = fieldDefinition.association;
if (!association) {
return;
}
const associatedConfiguration = association
.getAssociatedEntityClass()
.getCompanionDefinition().entityConfiguration;
if (associatedConfiguration !== entityConfiguration) {
return;
}
const associatedEntityLookupByField = association.associatedEntityLookupByField;
const loaderFactory = entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(entityClass)
.getLoaderFactory();
const mutatorFactory = entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(entityClass)
.getMutatorFactory();
let inboundReferenceEntities: readonly ReadonlyEntity<any, any, any, any>[];
if (associatedEntityLookupByField) {
inboundReferenceEntities = await loaderFactory
.forLoad(queryContext)
.enforcing()
.loadManyByFieldEqualingAsync(
fieldName,
entity.getField(associatedEntityLookupByField as any)
);
} else {
inboundReferenceEntities = await loaderFactory
.forLoad(queryContext)
.enforcing()
.loadManyByFieldEqualingAsync(fieldName, entity.getID());
}
switch (association.edgeDeletionBehavior) {
case undefined:
case EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE: {
await Promise.all(
inboundReferenceEntities.map((inboundReferenceEntity) =>
mutatorFactory
.forDelete(inboundReferenceEntity, queryContext)
.deleteInTransactionAsync(
processedEntityIdentifiers,
/* skipDatabaseDeletion */ true // deletion is handled by DB
)
)
);
break;
}
case EntityEdgeDeletionBehavior.SET_NULL: {
await Promise.all(
inboundReferenceEntities.map((inboundReferenceEntity) =>
mutatorFactory
.forUpdate(inboundReferenceEntity, queryContext)
.setField(fieldName, null)
.enforceUpdateAsync()
)
);
break;
}
case EntityEdgeDeletionBehavior.CASCADE_DELETE: {
await Promise.all(
inboundReferenceEntities.map((inboundReferenceEntity) =>
mutatorFactory
.forDelete(inboundReferenceEntity, queryContext)
.deleteInTransactionAsync(
processedEntityIdentifiers,
/* skipDatabaseDeletion */ false
)
)
);
}
}
}
);
})
);
}
}
+27 -4
View File
@@ -1,6 +1,9 @@
import Entity, { IEntityClass } from './Entity';
import EntityConfiguration from './EntityConfiguration';
import EntityDatabaseAdapter from './EntityDatabaseAdapter';
import EntityLoaderFactory from './EntityLoaderFactory';
import EntityMutationTriggerConfiguration from './EntityMutationTriggerConfiguration';
import EntityMutationValidator from './EntityMutationValidator';
import { CreateMutator, UpdateMutator, DeleteMutator } from './EntityMutator';
import EntityPrivacyPolicy from './EntityPrivacyPolicy';
import { EntityQueryContext } from './EntityQueryContext';
@@ -25,7 +28,7 @@ export default class EntityMutatorFactory<
TSelectedFields extends keyof TFields = keyof TFields
> {
constructor(
private readonly idField: keyof TFields,
private readonly entityConfiguration: EntityConfiguration<TFields>,
private readonly entityClass: IEntityClass<
TFields,
TID,
@@ -35,6 +38,20 @@ export default class EntityMutatorFactory<
TSelectedFields
>,
private readonly privacyPolicy: TPrivacyPolicy,
private readonly mutationValidators: EntityMutationValidator<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[],
private readonly mutationTriggers: EntityMutationTriggerConfiguration<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>,
private readonly entityLoaderFactory: EntityLoaderFactory<
TFields,
TID,
@@ -60,9 +77,11 @@ export default class EntityMutatorFactory<
return new CreateMutator(
viewerContext,
queryContext,
this.idField,
this.entityConfiguration,
this.entityClass,
this.privacyPolicy,
this.mutationValidators,
this.mutationTriggers,
this.entityLoaderFactory,
this.databaseAdapter,
this.metricsAdapter
@@ -82,9 +101,11 @@ export default class EntityMutatorFactory<
return new UpdateMutator(
existingEntity.getViewerContext(),
queryContext,
this.idField,
this.entityConfiguration,
this.entityClass,
this.privacyPolicy,
this.mutationValidators,
this.mutationTriggers,
this.entityLoaderFactory,
this.databaseAdapter,
this.metricsAdapter,
@@ -104,9 +125,11 @@ export default class EntityMutatorFactory<
return new DeleteMutator(
existingEntity.getViewerContext(),
queryContext,
this.idField,
this.entityConfiguration,
this.entityClass,
this.privacyPolicy,
this.mutationValidators,
this.mutationTriggers,
this.entityLoaderFactory,
this.databaseAdapter,
this.metricsAdapter,
+50 -7
View File
@@ -1,3 +1,9 @@
import { v4 as uuidv4 } from 'uuid';
import EntityQueryContextProvider from './EntityQueryContextProvider';
export type PostCommitCallback = (...args: any) => Promise<any>;
/**
* Entity framework representation of transactional and non-transactional database
* query execution units.
@@ -8,21 +14,58 @@
export abstract class EntityQueryContext {
constructor(private readonly queryInterface: any) {}
abstract isInTransaction(): boolean;
abstract isInTransaction(): this is EntityTransactionalQueryContext;
getQueryInterface(): any {
return this.queryInterface;
}
}
export class EntityTransactionalQueryContext extends EntityQueryContext {
isInTransaction(): boolean {
return true;
}
abstract async runInTransactionIfNotInTransactionAsync<T>(
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>
): Promise<T>;
}
export class EntityNonTransactionalQueryContext extends EntityQueryContext {
isInTransaction(): boolean {
constructor(
queryInterface: any,
private readonly entityQueryContextProvider: EntityQueryContextProvider
) {
super(queryInterface);
}
isInTransaction(): this is EntityTransactionalQueryContext {
return false;
}
async runInTransactionIfNotInTransactionAsync<T>(
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>
): Promise<T> {
return await this.entityQueryContextProvider.runInTransactionAsync(transactionScope);
}
}
export class EntityTransactionalQueryContext extends EntityQueryContext {
public readonly transactionID = uuidv4();
private readonly postCommitCallbacks: PostCommitCallback[] = [];
public appendPostCommitCallback(callback: PostCommitCallback): void {
this.postCommitCallbacks.push(callback);
}
public async runPostCommitCallbacksAsync(): Promise<void> {
const callbacks = [...this.postCommitCallbacks];
this.postCommitCallbacks.length = 0;
await Promise.all(callbacks.map((callback) => callback()));
}
isInTransaction(): this is EntityTransactionalQueryContext {
return true;
}
async runInTransactionIfNotInTransactionAsync<T>(
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>
): Promise<T> {
return await transactionScope(this);
}
}
@@ -0,0 +1,46 @@
import {
EntityTransactionalQueryContext,
EntityNonTransactionalQueryContext,
} from './EntityQueryContext';
/**
* A query context provider vends transactional and non-transactional query contexts.
*/
export default abstract class EntityQueryContextProvider {
/**
* Vend a regular (non-transactional) entity query context.
*/
public getQueryContext(): EntityNonTransactionalQueryContext {
return new EntityNonTransactionalQueryContext(this.getQueryInterface(), this);
}
/**
* Get the query interface for constructing a query context.
*/
protected abstract getQueryInterface(): any;
/**
* Vend a transaction runner for use in {@link runInTransactionAsync}.
*/
protected abstract createTransactionRunner<T>(): (
transactionScope: (queryInterface: any) => Promise<T>
) => Promise<T>;
/**
* Start a transaction and execute the provided transaction-scoped closure within the transaction.
* @param transactionScope - async callback to execute within the transaction
*/
async runInTransactionAsync<T>(
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>
): Promise<T> {
const [returnedValue, queryContext] = await this.createTransactionRunner<
[T, EntityTransactionalQueryContext]
>()(async (queryInterface) => {
const queryContext = new EntityTransactionalQueryContext(queryInterface);
const result = await transactionScope(queryContext);
return [result, queryContext];
});
await queryContext.runPostCommitCallbacksAsync();
return returnedValue;
}
}
@@ -1,22 +0,0 @@
import {
EntityNonTransactionalQueryContext,
EntityTransactionalQueryContext,
} from './EntityQueryContext';
/**
* A query context provider vends transactional and non-transactional query contexts.
*/
export default interface IEntityQueryContextProvider {
/**
* Vend a regular (non-transactional) entity query context.
*/
getRegularEntityQueryContext(): EntityNonTransactionalQueryContext;
/**
* Start a transaction and execute the provided transaction-scoped closure within the transaction.
* @param transactionScope - async callback to execute within the transaction
*/
runInTransactionAsync<T>(
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>
): Promise<T>;
}
+25 -9
View File
@@ -1,12 +1,13 @@
import invariant from 'invariant';
import { pick } from 'lodash';
import { IEntityClass } from './Entity';
import EntityAssociationLoader from './EntityAssociationLoader';
import { EntityCompanionDefinition } from './EntityCompanionProvider';
import EntityLoader from './EntityLoader';
import EntityPrivacyPolicy from './EntityPrivacyPolicy';
import { EntityQueryContext, EntityTransactionalQueryContext } from './EntityQueryContext';
import ViewerContext from './ViewerContext';
import { pick } from './entityUtils';
/**
* A readonly entity exposes only the read functionality of an Entity. Used as the base
@@ -36,14 +37,24 @@ export default abstract class ReadonlyEntity<
private readonly viewerContext: TViewerContext,
private readonly databaseFields: Readonly<TFields>
) {
const idField = (this.constructor as any).getCompanionDefinition().entityConfiguration
.idField as keyof Pick<TFields, TSelectedFields>;
const companionDefinition = (this
.constructor as any).getCompanionDefinition() as EntityCompanionDefinition<
TFields,
TID,
TViewerContext,
this,
EntityPrivacyPolicy<TFields, TID, TViewerContext, this, TSelectedFields>,
TSelectedFields
>;
const idField = companionDefinition.entityConfiguration.idField as keyof Pick<
TFields,
TSelectedFields
>;
const id = databaseFields[idField];
invariant(id, 'must provide ID to create an entity');
this.id = id as any;
const entitySelectedFields = (this.constructor as any).getCompanionDefinition()
.entitySelectedFields as (keyof TFields)[];
const entitySelectedFields = companionDefinition.entitySelectedFields as (keyof TFields)[];
this.rawFields = pick(databaseFields, entitySelectedFields);
}
@@ -51,6 +62,10 @@ export default abstract class ReadonlyEntity<
return `${this.constructor.name}[${this.getID()}]`;
}
getUniqueIdentifier(): string {
return this.toString();
}
/**
* @returns the ViewerContext authorized to read this entity
*/
@@ -107,7 +122,7 @@ export default abstract class ReadonlyEntity<
* Get the regular (non-transactional) query context for this entity.
* @param viewerContext - viewer context of calling user
*/
static getRegularEntityQueryContext<
static getQueryContext<
TMFields,
TMID,
TMViewerContext extends ViewerContext,
@@ -135,7 +150,7 @@ export default abstract class ReadonlyEntity<
return viewerContext
.getViewerScopedEntityCompanionForClass(this)
.getQueryContextProvider()
.getRegularEntityQueryContext();
.getQueryContext();
}
/**
@@ -173,7 +188,8 @@ export default abstract class ReadonlyEntity<
return await viewerContext
.getViewerScopedEntityCompanionForClass(this)
.getQueryContextProvider()
.runInTransactionAsync(transactionScope);
.getQueryContext()
.runInTransactionIfNotInTransactionAsync(transactionScope);
}
/**
@@ -208,7 +224,7 @@ export default abstract class ReadonlyEntity<
queryContext: EntityQueryContext = viewerContext
.getViewerScopedEntityCompanionForClass(this)
.getQueryContextProvider()
.getRegularEntityQueryContext()
.getQueryContext()
): EntityLoader<TMFields, TMID, TMViewerContext, TMEntity, TMPrivacyPolicy, TMSelectedFields> {
return viewerContext
.getViewerScopedEntityCompanionForClass(this)
@@ -1,6 +1,6 @@
import EntityCompanion from './EntityCompanion';
import EntityPrivacyPolicy from './EntityPrivacyPolicy';
import IEntityQueryContextProvider from './IEntityQueryContextProvider';
import EntityQueryContextProvider from './EntityQueryContextProvider';
import ReadonlyEntity from './ReadonlyEntity';
import ViewerContext from './ViewerContext';
import ViewerScopedEntityLoaderFactory from './ViewerScopedEntityLoaderFactory';
@@ -73,7 +73,7 @@ export default class ViewerScopedEntityCompanion<
/**
* Get the query context provider for this entity.
*/
getQueryContextProvider(): IEntityQueryContextProvider {
getQueryContextProvider(): EntityQueryContextProvider {
return this.entityCompanion.getQueryContextProvider();
}
}
@@ -283,7 +283,13 @@ describe(EnforcingEntityLoader, () => {
const loaderProperties = Object.getOwnPropertyNames(EntityLoader.prototype);
// ensure known differences still exist for sanity check
const knownLoaderOnlyDifferences = ['enforcing', 'invalidateFieldsAsync'];
const knownLoaderOnlyDifferences = [
'enforcing',
'invalidateFieldsAsync',
'invalidateEntityAsync',
'invalidateFieldsTransactionalAsync',
'tryConstructEntities',
];
expect(loaderProperties).toEqual(expect.arrayContaining(knownLoaderOnlyDifferences));
const loaderPropertiesWithoutKnownDifferences = loaderProperties.filter(
@@ -9,7 +9,7 @@ import { createUnitTestEntityCompanionProvider } from '../utils/testing/createUn
describe(EntityAssociationLoader, () => {
describe('loadAssociatedEntityAsync', () => {
it('loads associated entities by ID', async () => {
it('loads associated entities by ID and correctly handles a null value', async () => {
const companionProvider = createUnitTestEntityCompanionProvider();
const viewerContext = new TestViewerContext(companionProvider);
const testOtherEntity = await enforceAsyncResult(
@@ -24,6 +24,11 @@ describe(EntityAssociationLoader, () => {
testEntity.associationLoader().loadAssociatedEntityAsync('stringField', TestEntity)
);
expect(loadedOther.getID()).toEqual(testOtherEntity.getID());
const loadedOther2 = await enforceAsyncResult(
testEntity.associationLoader().loadAssociatedEntityAsync('nullableField', TestEntity)
);
expect(loadedOther2).toBeNull();
});
});
@@ -76,6 +81,18 @@ describe(EntityAssociationLoader, () => {
.loadAssociatedEntityByFieldEqualingAsync('stringField', TestEntity, 'customIdField');
expect(loadedOtherResult).toBeNull();
});
it('returns null when load-by field is null', async () => {
const companionProvider = createUnitTestEntityCompanionProvider();
const viewerContext = new TestViewerContext(companionProvider);
const testEntity = await enforceAsyncResult(
TestEntity.creator(viewerContext).setField('stringField', 'blah').createAsync()
);
const loadedOtherResult = await testEntity
.associationLoader()
.loadAssociatedEntityByFieldEqualingAsync('nullableField', TestEntity, 'customIdField');
expect(loadedOtherResult).toBeNull();
});
});
describe('loadManyAssociatedEntitiesByFieldEqualingAsync', () => {
@@ -102,6 +119,22 @@ describe(EntityAssociationLoader, () => {
expect(loaded.find((e) => e.getID() === testOtherEntity1.getID())).not.toBeUndefined();
expect(loaded.find((e) => e.getID() === testOtherEntity2.getID())).not.toBeUndefined();
});
it('returns empty results when field being queried by is null', async () => {
const companionProvider = createUnitTestEntityCompanionProvider();
const viewerContext = new TestViewerContext(companionProvider);
const testEntity = await enforceAsyncResult(TestEntity.creator(viewerContext).createAsync());
const loaded = await enforceResultsAsync(
testEntity
.associationLoader()
.loadManyAssociatedEntitiesByFieldEqualingAsync(
'nullableField',
TestEntity,
'stringField'
)
);
expect(loaded).toHaveLength(0);
});
});
describe('loadAssociatedEntityThroughAsync', () => {
@@ -213,5 +246,22 @@ describe(EntityAssociationLoader, () => {
]);
expect(loaded2Result).toBeNull();
});
it('returns null when chain loading by field is null', async () => {
const companionProvider = createUnitTestEntityCompanionProvider();
const viewerContext = new TestViewerContext(companionProvider);
const testEntity = await enforceAsyncResult(
TestEntity.creator(viewerContext).setField('nullableField', null).createAsync()
);
const loadedResult = await testEntity.associationLoader().loadAssociatedEntityThroughAsync([
{
associatedEntityClass: TestEntity,
fieldIdentifyingAssociatedEntity: 'nullableField',
},
]);
expect(loadedResult).toBeNull();
});
});
});
@@ -19,6 +19,8 @@ describe(EntityCompanion, () => {
TestEntity,
instance(tableDataCoordinatorMock),
TestEntityPrivacyPolicy,
[],
{},
instance(mock<IEntityMetricsAdapter>())
);
expect(companion.getLoaderFactory()).toBeInstanceOf(EntityLoaderFactory);
@@ -209,14 +209,6 @@ describe(EntityDatabaseAdapter, () => {
});
describe('deleteAsync', () => {
it('throws when update result count zero', async () => {
const queryContext = instance(mock(EntityQueryContext));
const adapter = new TestEntityDatabaseAdapter({ deleteCount: 0 });
await expect(adapter.deleteAsync(queryContext, 'customIdField', 'wat')).rejects.toThrowError(
'No deletions from database adapter delet'
);
});
it('throws when update result count greater than 1', async () => {
const queryContext = instance(mock(EntityQueryContext));
const adapter = new TestEntityDatabaseAdapter({ deleteCount: 2 });
@@ -0,0 +1,319 @@
import Entity from '../Entity';
import {
DatabaseAdapterFlavor,
CacheAdapterFlavor,
EntityCompanionDefinition,
} from '../EntityCompanionProvider';
import EntityConfiguration from '../EntityConfiguration';
import { UUIDField, EntityEdgeDeletionBehavior } from '../EntityFields';
import EntityPrivacyPolicy from '../EntityPrivacyPolicy';
import { CacheStatus } from '../internal/ReadThroughEntityCache';
import AlwaysAllowPrivacyPolicyRule from '../rules/AlwaysAllowPrivacyPolicyRule';
import TestViewerContext from '../testfixtures/TestViewerContext';
import { InMemoryFullCacheStubCacheAdapter } from '../utils/testing/StubCacheAdapter';
import { createUnitTestEntityCompanionProvider } from '../utils/testing/createUnitTestEntityCompanionProvider';
interface ParentFields {
id: string;
}
interface ChildFields {
id: string;
parent_id: string;
}
interface GrandChildFields {
id: string;
parent_id: string;
}
class TestEntityPrivacyPolicy extends EntityPrivacyPolicy<
any,
string,
TestViewerContext,
any,
any
> {
protected readonly readRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly createRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly updateRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly deleteRules = [new AlwaysAllowPrivacyPolicyRule()];
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const makeEntityClasses = (edgeDeletionBehavior: EntityEdgeDeletionBehavior) => {
class ParentEntity extends Entity<ParentFields, string, TestViewerContext> {
static getCompanionDefinition(): EntityCompanionDefinition<
ParentFields,
string,
TestViewerContext,
ParentEntity,
TestEntityPrivacyPolicy
> {
return parentEntityCompanion;
}
}
class ChildEntity extends Entity<ChildFields, string, TestViewerContext> {
static getCompanionDefinition(): EntityCompanionDefinition<
ChildFields,
string,
TestViewerContext,
ChildEntity,
TestEntityPrivacyPolicy
> {
return childEntityCompanion;
}
}
class GrandChildEntity extends Entity<GrandChildFields, string, TestViewerContext> {
static getCompanionDefinition(): EntityCompanionDefinition<
GrandChildFields,
string,
TestViewerContext,
GrandChildEntity,
TestEntityPrivacyPolicy
> {
return grandChildEntityCompanion;
}
}
const parentEntityConfiguration = new EntityConfiguration<ParentFields>({
idField: 'id',
tableName: 'parents',
getInboundEdges: () => [ChildEntity],
schema: {
id: new UUIDField({
columnName: 'id',
cache: true,
}),
},
databaseAdapterFlavor: DatabaseAdapterFlavor.POSTGRES,
cacheAdapterFlavor: CacheAdapterFlavor.REDIS,
});
const childEntityConfiguration = new EntityConfiguration<ChildFields>({
idField: 'id',
tableName: 'children',
getInboundEdges: () => [GrandChildEntity],
schema: {
id: new UUIDField({
columnName: 'id',
cache: true,
}),
parent_id: new UUIDField({
columnName: 'parent_id',
cache: true,
association: {
getAssociatedEntityClass: () => ParentEntity,
edgeDeletionBehavior,
},
}),
},
databaseAdapterFlavor: DatabaseAdapterFlavor.POSTGRES,
cacheAdapterFlavor: CacheAdapterFlavor.REDIS,
});
const grandChildEntityConfiguration = new EntityConfiguration<GrandChildFields>({
idField: 'id',
tableName: 'grandchildren',
schema: {
id: new UUIDField({
columnName: 'id',
cache: true,
}),
parent_id: new UUIDField({
columnName: 'parent_id',
cache: true,
association: {
getAssociatedEntityClass: () => ChildEntity,
edgeDeletionBehavior,
},
}),
},
databaseAdapterFlavor: DatabaseAdapterFlavor.POSTGRES,
cacheAdapterFlavor: CacheAdapterFlavor.REDIS,
});
const parentEntityCompanion = new EntityCompanionDefinition({
entityClass: ParentEntity,
entityConfiguration: parentEntityConfiguration,
privacyPolicyClass: TestEntityPrivacyPolicy,
});
const childEntityCompanion = new EntityCompanionDefinition({
entityClass: ChildEntity,
entityConfiguration: childEntityConfiguration,
privacyPolicyClass: TestEntityPrivacyPolicy,
});
const grandChildEntityCompanion = new EntityCompanionDefinition({
entityClass: GrandChildEntity,
entityConfiguration: grandChildEntityConfiguration,
privacyPolicyClass: TestEntityPrivacyPolicy,
});
return {
ParentEntity,
ChildEntity,
GrandChildEntity,
};
};
describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
describe('EntityEdgeDeletionBehavior.CASCADE_DELETE', () => {
it('deletes', async () => {
const { ParentEntity, ChildEntity, GrandChildEntity } = makeEntityClasses(
EntityEdgeDeletionBehavior.CASCADE_DELETE
);
const companionProvider = createUnitTestEntityCompanionProvider();
const viewerContext = new TestViewerContext(companionProvider);
const parent = await ParentEntity.creator(viewerContext).enforceCreateAsync();
const child = await ChildEntity.creator(viewerContext)
.setField('parent_id', parent.getID())
.enforceCreateAsync();
const grandchild = await GrandChildEntity.creator(viewerContext)
.setField('parent_id', child.getID())
.enforceCreateAsync();
await expect(
ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID())
).resolves.not.toBeNull();
await expect(
ChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(child.getID())
).resolves.not.toBeNull();
await expect(
GrandChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(grandchild.getID())
).resolves.not.toBeNull();
await ParentEntity.enforceDeleteAsync(parent);
await expect(
ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID())
).resolves.toBeNull();
await expect(
ChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(child.getID())
).resolves.toBeNull();
await expect(
GrandChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(grandchild.getID())
).resolves.toBeNull();
});
});
describe('EntityEdgeDeletionBehavior.SET_NULL', () => {
it('sets null', async () => {
const { ParentEntity, ChildEntity, GrandChildEntity } = makeEntityClasses(
EntityEdgeDeletionBehavior.SET_NULL
);
const companionProvider = createUnitTestEntityCompanionProvider();
const viewerContext = new TestViewerContext(companionProvider);
const parent = await ParentEntity.creator(viewerContext).enforceCreateAsync();
const child = await ChildEntity.creator(viewerContext)
.setField('parent_id', parent.getID())
.enforceCreateAsync();
const grandchild = await GrandChildEntity.creator(viewerContext)
.setField('parent_id', child.getID())
.enforceCreateAsync();
await expect(
ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID())
).resolves.not.toBeNull();
await expect(
ChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(child.getID())
).resolves.not.toBeNull();
await expect(
GrandChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(grandchild.getID())
).resolves.not.toBeNull();
await ParentEntity.enforceDeleteAsync(parent);
await expect(
ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID())
).resolves.toBeNull();
const loadedChild = await ChildEntity.loader(viewerContext)
.enforcing()
.loadByIDAsync(child.getID());
expect(loadedChild.getField('parent_id')).toBeNull();
const loadedGrandchild = await GrandChildEntity.loader(viewerContext)
.enforcing()
.loadByIDAsync(grandchild.getID());
expect(loadedGrandchild.getField('parent_id')).toEqual(loadedChild.getID());
});
});
describe('EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE', () => {
it('invalidates the cache', async () => {
const { ParentEntity, ChildEntity, GrandChildEntity } = makeEntityClasses(
EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE
);
const companionProvider = createUnitTestEntityCompanionProvider();
const viewerContext = new TestViewerContext(companionProvider);
const parent = await ParentEntity.creator(viewerContext).enforceCreateAsync();
const child = await ChildEntity.creator(viewerContext)
.setField('parent_id', parent.getID())
.enforceCreateAsync();
const grandchild = await GrandChildEntity.creator(viewerContext)
.setField('parent_id', child.getID())
.enforceCreateAsync();
await expect(
ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID())
).resolves.not.toBeNull();
await expect(
ChildEntity.loader(viewerContext)
.enforcing()
.loadByFieldEqualingAsync('parent_id', parent.getID())
).resolves.not.toBeNull();
await expect(
GrandChildEntity.loader(viewerContext)
.enforcing()
.loadByFieldEqualingAsync('parent_id', child.getID())
).resolves.not.toBeNull();
const childCacheAdapter = viewerContext.getViewerScopedEntityCompanionForClass(ChildEntity)[
'entityCompanion'
]['tableDataCoordinator']['cacheAdapter'] as InMemoryFullCacheStubCacheAdapter<ChildFields>;
const childCachedBefore = await childCacheAdapter.loadManyAsync('parent_id', [
parent.getID(),
]);
expect(childCachedBefore.get(parent.getID())?.status).toEqual(CacheStatus.HIT);
const grandChildCacheAdapter = viewerContext.getViewerScopedEntityCompanionForClass(
GrandChildEntity
)['entityCompanion']['tableDataCoordinator'][
'cacheAdapter'
] as InMemoryFullCacheStubCacheAdapter<ChildFields>;
const grandChildCachedBefore = await grandChildCacheAdapter.loadManyAsync('parent_id', [
child.getID(),
]);
expect(grandChildCachedBefore.get(child.getID())?.status).toEqual(CacheStatus.HIT);
await ParentEntity.enforceDeleteAsync(parent);
const childCachedAfter = await childCacheAdapter.loadManyAsync('parent_id', [parent.getID()]);
expect(childCachedAfter.get(parent.getID())?.status).toEqual(CacheStatus.MISS);
const grandChildCachedAfter = await grandChildCacheAdapter.loadManyAsync('parent_id', [
child.getID(),
]);
expect(grandChildCachedAfter.get(child.getID())?.status).toEqual(CacheStatus.MISS);
await expect(
ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID())
).resolves.toBeNull();
await expect(
ChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(child.getID())
).resolves.not.toBeNull();
await expect(
GrandChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(grandchild.getID())
).resolves.not.toBeNull();
});
});
});
@@ -2,7 +2,6 @@ import { enforceAsyncResult } from '@expo/results';
import { mock, instance, verify, spy, deepEqual, anyOfClass, anything, when } from 'ts-mockito';
import EntityLoader from '../EntityLoader';
import { EntityNonTransactionalQueryContext } from '../EntityQueryContext';
import ViewerContext from '../ViewerContext';
import { enforceResultsAsync } from '../entityUtils';
import EntityDataManager from '../internal/EntityDataManager';
@@ -21,7 +20,7 @@ describe(EntityLoader, () => {
it('loads entities', async () => {
const dateToInsert = new Date();
const viewerContext = instance(mock(ViewerContext));
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = StubQueryContextProvider.getQueryContext();
const databaseAdapter = new StubDatabaseAdapter<TestFields>(
testEntityConfiguration,
@@ -37,6 +36,7 @@ describe(EntityLoader, () => {
numberField: 5,
stringField: 'huh',
dateField: dateToInsert,
nullableField: null,
},
{
customIdField: 'world',
@@ -44,6 +44,7 @@ describe(EntityLoader, () => {
numberField: 3,
stringField: 'huh',
dateField: dateToInsert,
nullableField: null,
},
],
],
@@ -58,7 +59,8 @@ describe(EntityLoader, () => {
databaseAdapter,
entityCache,
StubQueryContextProvider,
instance(mock<IEntityMetricsAdapter>())
instance(mock<IEntityMetricsAdapter>()),
TestEntity.name
);
const entityLoader = new EntityLoader(
viewerContext,
@@ -96,7 +98,7 @@ describe(EntityLoader, () => {
const privacyPolicy = new TestEntityPrivacyPolicy();
const spiedPrivacyPolicy = spy(privacyPolicy);
const viewerContext = instance(mock(ViewerContext));
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = StubQueryContextProvider.getQueryContext();
const databaseAdapter = new StubDatabaseAdapter<TestFields>(
testEntityConfiguration,
@@ -112,6 +114,7 @@ describe(EntityLoader, () => {
numberField: 4,
testIndexedField: '4',
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'world',
@@ -119,6 +122,7 @@ describe(EntityLoader, () => {
numberField: 4,
testIndexedField: '5',
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'blah',
@@ -126,6 +130,7 @@ describe(EntityLoader, () => {
numberField: 4,
testIndexedField: '6',
dateField: new Date(),
nullableField: null,
},
],
],
@@ -139,7 +144,8 @@ describe(EntityLoader, () => {
databaseAdapter,
entityCache,
StubQueryContextProvider,
instance(mock<IEntityMetricsAdapter>())
instance(mock<IEntityMetricsAdapter>()),
TestEntity.name
);
const entityLoader = new EntityLoader(
viewerContext,
@@ -172,7 +178,7 @@ describe(EntityLoader, () => {
const spiedPrivacyPolicy = spy(privacyPolicy);
const viewerContext = instance(mock(ViewerContext));
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = StubQueryContextProvider.getQueryContext();
const databaseAdapter = new StubDatabaseAdapter<TestFields>(
testEntityConfiguration,
@@ -188,6 +194,7 @@ describe(EntityLoader, () => {
testIndexedField: '1',
numberField: 3,
dateField: new Date(),
nullableField: null,
},
],
],
@@ -201,7 +208,8 @@ describe(EntityLoader, () => {
databaseAdapter,
entityCache,
StubQueryContextProvider,
instance(mock<IEntityMetricsAdapter>())
instance(mock<IEntityMetricsAdapter>()),
TestEntity.name
);
const entityLoader = new EntityLoader(
viewerContext,
@@ -217,7 +225,7 @@ describe(EntityLoader, () => {
it('invalidates upon invalidate one', async () => {
const viewerContext = instance(mock(ViewerContext));
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = StubQueryContextProvider.getQueryContext();
const privacyPolicy = instance(mock(TestEntityPrivacyPolicy));
const dataManagerMock = mock(EntityDataManager);
const dataManagerInstance = instance(dataManagerMock);
@@ -239,7 +247,7 @@ describe(EntityLoader, () => {
it('invalidates upon invalidate by field', async () => {
const viewerContext = instance(mock(ViewerContext));
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = StubQueryContextProvider.getQueryContext();
const privacyPolicy = instance(mock(TestEntityPrivacyPolicy));
const dataManagerMock = mock(EntityDataManager);
const dataManagerInstance = instance(dataManagerMock);
@@ -258,9 +266,34 @@ describe(EntityLoader, () => {
).once();
});
it('invalidates upon invalidate by entity', async () => {
const viewerContext = instance(mock(ViewerContext));
const queryContext = StubQueryContextProvider.getQueryContext();
const privacyPolicy = instance(mock(TestEntityPrivacyPolicy));
const dataManagerMock = mock(EntityDataManager);
const dataManagerInstance = instance(dataManagerMock);
const entityMock = mock(TestEntity);
when(entityMock.getAllDatabaseFields()).thenReturn({ customIdField: 'hello' } as any);
const entityInstance = instance(entityMock);
const entityLoader = new EntityLoader(
viewerContext,
queryContext,
testEntityConfiguration.idField,
TestEntity,
privacyPolicy,
dataManagerInstance
);
await entityLoader.invalidateEntityAsync(entityInstance);
verify(
dataManagerMock.invalidateObjectFieldsAsync(deepEqual({ customIdField: 'hello' }))
).once();
});
it('returns error result when not allowed', async () => {
const viewerContext = instance(mock(ViewerContext));
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = StubQueryContextProvider.getQueryContext();
const privacyPolicyMock = mock(TestEntityPrivacyPolicy);
const dataManagerMock = mock(EntityDataManager);
@@ -294,7 +327,7 @@ describe(EntityLoader, () => {
it('throws upon database adapter error', async () => {
const viewerContext = instance(mock(ViewerContext));
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = StubQueryContextProvider.getQueryContext();
const privacyPolicy = instance(mock(TestEntityPrivacyPolicy));
const dataManagerMock = mock(EntityDataManager);
@@ -12,8 +12,13 @@ import {
import EntityDatabaseAdapter from '../EntityDatabaseAdapter';
import EntityLoaderFactory from '../EntityLoaderFactory';
import EntityMutationTriggerConfiguration, {
EntityMutationTrigger,
EntityNonTransactionalMutationTrigger,
} from '../EntityMutationTriggerConfiguration';
import EntityMutationValidator from '../EntityMutationValidator';
import EntityMutatorFactory from '../EntityMutatorFactory';
import { EntityQueryContext, EntityNonTransactionalQueryContext } from '../EntityQueryContext';
import { EntityTransactionalQueryContext, EntityQueryContext } from '../EntityQueryContext';
import ViewerContext from '../ViewerContext';
import { enforceResultsAsync } from '../entityUtils';
import EntityDataManager from '../internal/EntityDataManager';
@@ -34,6 +39,161 @@ import { NoCacheStubCacheAdapterProvider } from '../utils/testing/StubCacheAdapt
import StubDatabaseAdapter from '../utils/testing/StubDatabaseAdapter';
import StubQueryContextProvider from '../utils/testing/StubQueryContextProvider';
class TestMutationTrigger extends EntityMutationTrigger<
TestFields,
string,
ViewerContext,
TestEntity,
keyof TestFields
> {
async executeAsync(
_viewerContext: ViewerContext,
_queryContext: EntityQueryContext,
_entity: TestEntity
): Promise<void> {}
}
class TestNonTransactionalMutationTrigger extends EntityNonTransactionalMutationTrigger<
TestFields,
string,
ViewerContext,
TestEntity,
keyof TestFields
> {
async executeAsync(_viewerContext: ViewerContext, _entity: TestEntity): Promise<void> {}
}
const setUpMutationValidatorSpies = (
mutationValidators: EntityMutationValidator<
TestFields,
string,
ViewerContext,
TestEntity,
keyof TestFields
>[]
): EntityMutationValidator<TestFields, string, ViewerContext, TestEntity, keyof TestFields>[] => {
return mutationValidators.map((validator) => spy(validator));
};
const verifyValidatorCounts = (
viewerContext: ViewerContext,
mutationValidatorSpies: EntityMutationValidator<
TestFields,
string,
ViewerContext,
TestEntity,
keyof TestFields
>[],
expectedCalls: number
): void => {
for (const validator of mutationValidatorSpies) {
verify(
validator.executeAsync(
viewerContext,
anyOfClass(EntityTransactionalQueryContext),
anyOfClass(TestEntity)
)
).times(expectedCalls);
}
};
const setUpMutationTriggerSpies = (
mutationTriggers: EntityMutationTriggerConfiguration<
TestFields,
string,
ViewerContext,
TestEntity,
keyof TestFields
>
): EntityMutationTriggerConfiguration<
TestFields,
string,
ViewerContext,
TestEntity,
keyof TestFields
> => {
return {
beforeCreate: [spy(mutationTriggers.beforeCreate![0])],
afterCreate: [spy(mutationTriggers.afterCreate![0])],
beforeUpdate: [spy(mutationTriggers.beforeUpdate![0])],
afterUpdate: [spy(mutationTriggers.afterUpdate![0])],
beforeDelete: [spy(mutationTriggers.beforeDelete![0])],
afterDelete: [spy(mutationTriggers.afterDelete![0])],
beforeAll: [spy(mutationTriggers.beforeAll![0])],
afterAll: [spy(mutationTriggers.afterAll![0])],
afterCommit: [spy(mutationTriggers.afterCommit![0])],
};
};
const verifyTriggerCounts = (
viewerContext: ViewerContext,
mutationTriggerSpies: EntityMutationTriggerConfiguration<
TestFields,
string,
ViewerContext,
TestEntity,
keyof TestFields
>,
executed: Record<
keyof Pick<
EntityMutationTriggerConfiguration<
TestFields,
string,
ViewerContext,
TestEntity,
keyof TestFields
>,
| 'beforeCreate'
| 'afterCreate'
| 'beforeUpdate'
| 'afterUpdate'
| 'beforeDelete'
| 'afterDelete'
>,
boolean
>
): void => {
Object.keys(executed).forEach((s) => {
if ((executed as any)[s]) {
verify(
(mutationTriggerSpies as any)[s]![0].executeAsync(
viewerContext,
anyOfClass(EntityTransactionalQueryContext),
anyOfClass(TestEntity)
)
).once();
} else {
verify(
(mutationTriggerSpies as any)[s]![0].executeAsync(
viewerContext,
anyOfClass(EntityTransactionalQueryContext),
anyOfClass(TestEntity)
)
).never();
}
});
verify(
mutationTriggerSpies.beforeAll![0].executeAsync(
viewerContext,
anyOfClass(EntityTransactionalQueryContext),
anyOfClass(TestEntity)
)
).once();
verify(
mutationTriggerSpies.afterAll![0].executeAsync(
viewerContext,
anyOfClass(EntityTransactionalQueryContext),
anyOfClass(TestEntity)
)
).once();
verify(
mutationTriggerSpies.afterCommit![0].executeAsync(viewerContext, anyOfClass(TestEntity))
).once();
};
const createEntityMutatorFactory = (
existingObjects: TestFields[]
): {
@@ -54,7 +214,45 @@ const createEntityMutatorFactory = (
TestEntityPrivacyPolicy
>;
metricsAdapter: IEntityMetricsAdapter;
mutationValidators: EntityMutationValidator<
TestFields,
string,
ViewerContext,
TestEntity,
keyof TestFields
>[];
mutationTriggers: EntityMutationTriggerConfiguration<
TestFields,
string,
ViewerContext,
TestEntity,
keyof TestFields
>;
} => {
const mutationValidators: EntityMutationValidator<
TestFields,
string,
ViewerContext,
TestEntity,
keyof TestFields
>[] = [new TestMutationTrigger()];
const mutationTriggers: EntityMutationTriggerConfiguration<
TestFields,
string,
ViewerContext,
TestEntity,
keyof TestFields
> = {
beforeCreate: [new TestMutationTrigger()],
afterCreate: [new TestMutationTrigger()],
beforeUpdate: [new TestMutationTrigger()],
afterUpdate: [new TestMutationTrigger()],
beforeDelete: [new TestMutationTrigger()],
afterDelete: [new TestMutationTrigger()],
beforeAll: [new TestMutationTrigger()],
afterAll: [new TestMutationTrigger()],
afterCommit: [new TestNonTransactionalMutationTrigger()],
};
const privacyPolicy = new TestEntityPrivacyPolicy();
const databaseAdapter = new StubDatabaseAdapter<TestFields>(
testEntityConfiguration,
@@ -71,7 +269,8 @@ const createEntityMutatorFactory = (
databaseAdapter,
entityCache,
StubQueryContextProvider,
metricsAdapter
metricsAdapter,
TestEntity.name
);
const entityLoaderFactory = new EntityLoaderFactory(
testEntityConfiguration.idField,
@@ -80,9 +279,11 @@ const createEntityMutatorFactory = (
dataManager
);
const entityMutatorFactory = new EntityMutatorFactory(
testEntityConfiguration.idField,
testEntityConfiguration,
TestEntity,
privacyPolicy,
mutationValidators,
mutationTriggers,
entityLoaderFactory,
databaseAdapter,
metricsAdapter
@@ -92,55 +293,163 @@ const createEntityMutatorFactory = (
entityLoaderFactory,
entityMutatorFactory,
metricsAdapter,
mutationValidators,
mutationTriggers,
};
};
describe(EntityMutatorFactory, () => {
it('creates entities and checks privacy', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = mock<EntityQueryContext>();
const { privacyPolicy, entityMutatorFactory } = createEntityMutatorFactory([
{
customIdField: 'hello',
stringField: 'huh',
testIndexedField: '4',
numberField: 1,
dateField: new Date(),
},
{
customIdField: 'world',
stringField: 'huh',
testIndexedField: '5',
numberField: 1,
dateField: new Date(),
},
]);
describe('forCreate', () => {
it('creates entities', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = StubQueryContextProvider.getQueryContext();
const { entityMutatorFactory } = createEntityMutatorFactory([
{
customIdField: 'hello',
stringField: 'huh',
testIndexedField: '4',
numberField: 1,
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'world',
stringField: 'huh',
testIndexedField: '5',
numberField: 1,
dateField: new Date(),
nullableField: null,
},
]);
const newEntity = await entityMutatorFactory
.forCreate(viewerContext, queryContext)
.setField('stringField', 'huh')
.enforceCreateAsync();
expect(newEntity).toBeTruthy();
});
const spiedPrivacyPolicy = spy(privacyPolicy);
it('checks privacy', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = StubQueryContextProvider.getQueryContext();
const { privacyPolicy, entityMutatorFactory } = createEntityMutatorFactory([
{
customIdField: 'hello',
stringField: 'huh',
testIndexedField: '4',
numberField: 1,
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'world',
stringField: 'huh',
testIndexedField: '5',
numberField: 1,
dateField: new Date(),
nullableField: null,
},
]);
const newEntity = await entityMutatorFactory
.forCreate(viewerContext, queryContext)
.setField('stringField', 'huh')
.enforceCreateAsync();
const spiedPrivacyPolicy = spy(privacyPolicy);
expect(newEntity).toBeTruthy();
await entityMutatorFactory
.forCreate(viewerContext, queryContext)
.setField('stringField', 'huh')
.enforceCreateAsync();
verify(
spiedPrivacyPolicy.authorizeCreateAsync(viewerContext, queryContext, anyOfClass(TestEntity))
).once();
verify(
spiedPrivacyPolicy.authorizeCreateAsync(
viewerContext,
anyOfClass(EntityTransactionalQueryContext),
anyOfClass(TestEntity)
)
).once();
});
it('executes triggers', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = StubQueryContextProvider.getQueryContext();
const { mutationTriggers, entityMutatorFactory } = createEntityMutatorFactory([
{
customIdField: 'hello',
stringField: 'huh',
testIndexedField: '4',
numberField: 1,
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'world',
stringField: 'huh',
testIndexedField: '5',
numberField: 1,
dateField: new Date(),
nullableField: null,
},
]);
const triggerSpies = setUpMutationTriggerSpies(mutationTriggers);
await entityMutatorFactory
.forCreate(viewerContext, queryContext)
.setField('stringField', 'huh')
.enforceCreateAsync();
verifyTriggerCounts(viewerContext, triggerSpies, {
beforeCreate: true,
afterCreate: true,
beforeUpdate: false,
afterUpdate: false,
beforeDelete: false,
afterDelete: false,
});
});
it('executes validators', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = StubQueryContextProvider.getQueryContext();
const { mutationValidators, entityMutatorFactory } = createEntityMutatorFactory([
{
customIdField: 'hello',
stringField: 'huh',
testIndexedField: '4',
numberField: 1,
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'world',
stringField: 'huh',
testIndexedField: '5',
numberField: 1,
dateField: new Date(),
nullableField: null,
},
]);
const validatorSpies = setUpMutationValidatorSpies(mutationValidators);
await entityMutatorFactory
.forCreate(viewerContext, queryContext)
.setField('stringField', 'huh')
.enforceCreateAsync();
verifyValidatorCounts(viewerContext, validatorSpies, 1);
});
});
it('updates entities and checks privacy', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = mock<EntityQueryContext>();
const { privacyPolicy, entityMutatorFactory, entityLoaderFactory } = createEntityMutatorFactory(
[
describe('forUpdate', () => {
it('updates entities', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = StubQueryContextProvider.getQueryContext();
const { entityMutatorFactory, entityLoaderFactory } = createEntityMutatorFactory([
{
customIdField: 'hello',
stringField: 'huh',
testIndexedField: '3',
numberField: 3,
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'world',
@@ -148,73 +457,296 @@ describe(EntityMutatorFactory, () => {
testIndexedField: '4',
numberField: 3,
dateField: new Date(),
nullableField: null,
},
]
);
]);
const spiedPrivacyPolicy = spy(privacyPolicy);
const existingEntity = await enforceAsyncResult(
entityLoaderFactory.forLoad(viewerContext, queryContext).loadByIDAsync('world')
);
const existingEntity = await enforceAsyncResult(
entityLoaderFactory.forLoad(viewerContext, queryContext).loadByIDAsync('world')
);
const updatedEntity = await entityMutatorFactory
.forUpdate(existingEntity, queryContext)
.setField('stringField', 'huh2')
.enforceUpdateAsync();
const updatedEntity = await entityMutatorFactory
.forUpdate(existingEntity, queryContext)
.setField('stringField', 'huh2')
.enforceUpdateAsync();
expect(updatedEntity).toBeTruthy();
expect(updatedEntity.getAllFields()).not.toMatchObject(existingEntity.getAllFields());
expect(updatedEntity.getField('stringField')).toEqual('huh2');
expect(updatedEntity).toBeTruthy();
expect(updatedEntity.getAllFields()).not.toMatchObject(existingEntity.getAllFields());
expect(updatedEntity.getField('stringField')).toEqual('huh2');
const reloadedEntity = await enforceAsyncResult(
entityLoaderFactory.forLoad(viewerContext, queryContext).loadByIDAsync('world')
);
expect(reloadedEntity.getAllFields()).toMatchObject(updatedEntity.getAllFields());
});
const reloadedEntity = await enforceAsyncResult(
entityLoaderFactory.forLoad(viewerContext, queryContext).loadByIDAsync('world')
);
expect(reloadedEntity.getAllFields()).toMatchObject(updatedEntity.getAllFields());
it('checks privacy', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = StubQueryContextProvider.getQueryContext();
const {
privacyPolicy,
entityMutatorFactory,
entityLoaderFactory,
} = createEntityMutatorFactory([
{
customIdField: 'hello',
stringField: 'huh',
testIndexedField: '3',
numberField: 3,
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'world',
stringField: 'huh',
testIndexedField: '4',
numberField: 3,
dateField: new Date(),
nullableField: null,
},
]);
verify(
spiedPrivacyPolicy.authorizeUpdateAsync(viewerContext, queryContext, anyOfClass(TestEntity))
).once();
const spiedPrivacyPolicy = spy(privacyPolicy);
const existingEntity = await enforceAsyncResult(
entityLoaderFactory.forLoad(viewerContext, queryContext).loadByIDAsync('world')
);
await entityMutatorFactory
.forUpdate(existingEntity, queryContext)
.setField('stringField', 'huh2')
.enforceUpdateAsync();
verify(
spiedPrivacyPolicy.authorizeUpdateAsync(
viewerContext,
anyOfClass(EntityTransactionalQueryContext),
anyOfClass(TestEntity)
)
).once();
});
it('executes triggers', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = StubQueryContextProvider.getQueryContext();
const {
mutationTriggers,
entityMutatorFactory,
entityLoaderFactory,
} = createEntityMutatorFactory([
{
customIdField: 'hello',
stringField: 'huh',
testIndexedField: '3',
numberField: 3,
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'world',
stringField: 'huh',
testIndexedField: '4',
numberField: 3,
dateField: new Date(),
nullableField: null,
},
]);
const triggerSpies = setUpMutationTriggerSpies(mutationTriggers);
const existingEntity = await enforceAsyncResult(
entityLoaderFactory.forLoad(viewerContext, queryContext).loadByIDAsync('world')
);
await entityMutatorFactory
.forUpdate(existingEntity, queryContext)
.setField('stringField', 'huh2')
.enforceUpdateAsync();
verifyTriggerCounts(viewerContext, triggerSpies, {
beforeCreate: false,
afterCreate: false,
beforeUpdate: true,
afterUpdate: true,
beforeDelete: false,
afterDelete: false,
});
});
it('executes validators', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = StubQueryContextProvider.getQueryContext();
const {
mutationValidators,
entityMutatorFactory,
entityLoaderFactory,
} = createEntityMutatorFactory([
{
customIdField: 'hello',
stringField: 'huh',
testIndexedField: '3',
numberField: 3,
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'world',
stringField: 'huh',
testIndexedField: '4',
numberField: 3,
dateField: new Date(),
nullableField: null,
},
]);
const validatorSpies = setUpMutationValidatorSpies(mutationValidators);
const existingEntity = await enforceAsyncResult(
entityLoaderFactory.forLoad(viewerContext, queryContext).loadByIDAsync('world')
);
await entityMutatorFactory
.forUpdate(existingEntity, queryContext)
.setField('stringField', 'huh2')
.enforceUpdateAsync();
verifyValidatorCounts(viewerContext, validatorSpies, 1);
});
});
it('deletes entities and checks privacy', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = mock<EntityQueryContext>();
const { privacyPolicy, entityMutatorFactory, entityLoaderFactory } = createEntityMutatorFactory(
[
describe('forDelete', () => {
it('deletes entities', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = StubQueryContextProvider.getQueryContext();
const { entityMutatorFactory, entityLoaderFactory } = createEntityMutatorFactory([
{
customIdField: 'world',
stringField: 'huh',
testIndexedField: '3',
numberField: 3,
dateField: new Date(),
nullableField: null,
},
]
);
]);
const spiedPrivacyPolicy = spy(privacyPolicy);
const existingEntity = await enforceAsyncResult(
entityLoaderFactory.forLoad(viewerContext, queryContext).loadByIDAsync('world')
);
expect(existingEntity).toBeTruthy();
await entityMutatorFactory.forDelete(existingEntity, queryContext).enforceDeleteAsync();
await expect(
enforceAsyncResult(
const existingEntity = await enforceAsyncResult(
entityLoaderFactory.forLoad(viewerContext, queryContext).loadByIDAsync('world')
)
).rejects.toBeInstanceOf(Error);
);
expect(existingEntity).toBeTruthy();
verify(
spiedPrivacyPolicy.authorizeDeleteAsync(viewerContext, queryContext, anyOfClass(TestEntity))
).once();
await entityMutatorFactory.forDelete(existingEntity, queryContext).enforceDeleteAsync();
await expect(
enforceAsyncResult(
entityLoaderFactory.forLoad(viewerContext, queryContext).loadByIDAsync('world')
)
).rejects.toBeInstanceOf(Error);
});
it('checks privacy', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = StubQueryContextProvider.getQueryContext();
const {
privacyPolicy,
entityMutatorFactory,
entityLoaderFactory,
} = createEntityMutatorFactory([
{
customIdField: 'world',
stringField: 'huh',
testIndexedField: '3',
numberField: 3,
dateField: new Date(),
nullableField: null,
},
]);
const spiedPrivacyPolicy = spy(privacyPolicy);
const existingEntity = await enforceAsyncResult(
entityLoaderFactory.forLoad(viewerContext, queryContext).loadByIDAsync('world')
);
await entityMutatorFactory.forDelete(existingEntity, queryContext).enforceDeleteAsync();
verify(
spiedPrivacyPolicy.authorizeDeleteAsync(
viewerContext,
anyOfClass(EntityTransactionalQueryContext),
anyOfClass(TestEntity)
)
).once();
});
it('executes triggers', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = StubQueryContextProvider.getQueryContext();
const {
mutationTriggers,
entityMutatorFactory,
entityLoaderFactory,
} = createEntityMutatorFactory([
{
customIdField: 'world',
stringField: 'huh',
testIndexedField: '3',
numberField: 3,
dateField: new Date(),
nullableField: null,
},
]);
const triggerSpies = setUpMutationTriggerSpies(mutationTriggers);
const existingEntity = await enforceAsyncResult(
entityLoaderFactory.forLoad(viewerContext, queryContext).loadByIDAsync('world')
);
await entityMutatorFactory.forDelete(existingEntity, queryContext).enforceDeleteAsync();
verifyTriggerCounts(viewerContext, triggerSpies, {
beforeCreate: false,
afterCreate: false,
beforeUpdate: false,
afterUpdate: false,
beforeDelete: true,
afterDelete: true,
});
});
it('does not execute validators', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = StubQueryContextProvider.getQueryContext();
const {
mutationValidators,
entityMutatorFactory,
entityLoaderFactory,
} = createEntityMutatorFactory([
{
customIdField: 'world',
stringField: 'huh',
testIndexedField: '3',
numberField: 3,
dateField: new Date(),
nullableField: null,
},
]);
const validatorSpies = setUpMutationValidatorSpies(mutationValidators);
const existingEntity = await enforceAsyncResult(
entityLoaderFactory.forLoad(viewerContext, queryContext).loadByIDAsync('world')
);
await entityMutatorFactory.forDelete(existingEntity, queryContext).enforceDeleteAsync();
verifyValidatorCounts(viewerContext, validatorSpies, 0);
});
});
it('invalidates cache for fields upon create', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = mock<EntityQueryContext>();
const queryContext = StubQueryContextProvider.getQueryContext();
const { entityMutatorFactory, entityLoaderFactory } = createEntityMutatorFactory([
{
customIdField: 'world',
@@ -222,6 +754,7 @@ describe(EntityMutatorFactory, () => {
testIndexedField: '3',
numberField: 3,
dateField: new Date(),
nullableField: null,
},
]);
@@ -249,7 +782,7 @@ describe(EntityMutatorFactory, () => {
it('returns error result when not authorized to create', async () => {
const viewerContext = instance(mock(ViewerContext));
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = StubQueryContextProvider.getQueryContext();
const privacyPolicyMock = mock(SimpleTestEntityPrivacyPolicy);
const databaseAdapter = instance(mock(EntityDatabaseAdapter));
const metricsAdapter = instance(mock<IEntityMetricsAdapter>());
@@ -271,29 +804,31 @@ describe(EntityMutatorFactory, () => {
when(
privacyPolicyMock.authorizeCreateAsync(
viewerContext,
queryContext,
anyOfClass(EntityTransactionalQueryContext),
anyOfClass(SimpleTestEntity)
)
).thenReject(rejectionError);
when(
privacyPolicyMock.authorizeUpdateAsync(
viewerContext,
queryContext,
anyOfClass(EntityTransactionalQueryContext),
anyOfClass(SimpleTestEntity)
)
).thenReject(rejectionError);
when(
privacyPolicyMock.authorizeDeleteAsync(
viewerContext,
queryContext,
anyOfClass(EntityTransactionalQueryContext),
anyOfClass(SimpleTestEntity)
)
).thenReject(rejectionError);
const entityMutatorFactory = new EntityMutatorFactory(
simpleTestEntityConfiguration.idField,
simpleTestEntityConfiguration,
SimpleTestEntity,
instance(privacyPolicyMock),
[],
{},
entityLoaderFactory,
databaseAdapter,
metricsAdapter
@@ -327,7 +862,7 @@ describe(EntityMutatorFactory, () => {
it('throws error when db adapter throws', async () => {
const viewerContext = instance(mock(ViewerContext));
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = StubQueryContextProvider.getQueryContext();
const privacyPolicy = instance(mock(SimpleTestEntityPrivacyPolicy));
const databaseAdapterMock = mock(EntityDatabaseAdapter);
const metricsAdapter = instance(mock<IEntityMetricsAdapter>());
@@ -346,18 +881,31 @@ describe(EntityMutatorFactory, () => {
const rejectionError = new Error();
when(databaseAdapterMock.insertAsync(queryContext, anything())).thenReject(rejectionError);
when(
databaseAdapterMock.updateAsync(queryContext, anything(), anything(), anything())
databaseAdapterMock.insertAsync(anyOfClass(EntityTransactionalQueryContext), anything())
).thenReject(rejectionError);
when(
databaseAdapterMock.updateAsync(
anyOfClass(EntityTransactionalQueryContext),
anything(),
anything(),
anything()
)
).thenReject(rejectionError);
when(
databaseAdapterMock.deleteAsync(
anyOfClass(EntityTransactionalQueryContext),
anything(),
anything()
)
).thenReject(rejectionError);
when(databaseAdapterMock.deleteAsync(queryContext, anything(), anything())).thenReject(
rejectionError
);
const entityMutatorFactory = new EntityMutatorFactory(
simpleTestEntityConfiguration.idField,
simpleTestEntityConfiguration,
SimpleTestEntity,
privacyPolicy,
[],
{},
entityLoaderFactory,
instance(databaseAdapterMock),
metricsAdapter
@@ -380,7 +928,7 @@ describe(EntityMutatorFactory, () => {
it('records metrics appropriately', async () => {
const viewerContext = mock<ViewerContext>();
const queryContext = mock<EntityQueryContext>();
const queryContext = StubQueryContextProvider.getQueryContext();
const { entityMutatorFactory, metricsAdapter } = createEntityMutatorFactory([]);
const spiedMetricsAdapter = spy(metricsAdapter);
@@ -404,6 +952,7 @@ describe(EntityMutatorFactory, () => {
spiedMetricsAdapter.logMutatorMutationEvent(
objectContaining({
type: EntityMetricsMutationType.CREATE,
entityClassName: TestEntity.name,
})
)
).once();
@@ -411,6 +960,7 @@ describe(EntityMutatorFactory, () => {
spiedMetricsAdapter.logMutatorMutationEvent(
objectContaining({
type: EntityMetricsMutationType.UPDATE,
entityClassName: TestEntity.name,
})
)
).once();
@@ -418,6 +968,7 @@ describe(EntityMutatorFactory, () => {
spiedMetricsAdapter.logMutatorMutationEvent(
objectContaining({
type: EntityMetricsMutationType.DELETE,
entityClassName: TestEntity.name,
})
)
).once();
@@ -0,0 +1,327 @@
import Entity from '../Entity';
import {
DatabaseAdapterFlavor,
CacheAdapterFlavor,
EntityCompanionDefinition,
} from '../EntityCompanionProvider';
import EntityConfiguration from '../EntityConfiguration';
import { UUIDField, EntityEdgeDeletionBehavior } from '../EntityFields';
import EntityPrivacyPolicy from '../EntityPrivacyPolicy';
import { CacheStatus } from '../internal/ReadThroughEntityCache';
import AlwaysAllowPrivacyPolicyRule from '../rules/AlwaysAllowPrivacyPolicyRule';
import TestViewerContext from '../testfixtures/TestViewerContext';
import { InMemoryFullCacheStubCacheAdapter } from '../utils/testing/StubCacheAdapter';
import { createUnitTestEntityCompanionProvider } from '../utils/testing/createUnitTestEntityCompanionProvider';
interface CategoryFields {
id: string;
parent_category_id: string | null;
}
class CategoryPrivacyPolicy extends EntityPrivacyPolicy<
CategoryFields,
string,
TestViewerContext,
any,
any
> {
protected readonly readRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly createRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly updateRules = [new AlwaysAllowPrivacyPolicyRule()];
protected readonly deleteRules = [new AlwaysAllowPrivacyPolicyRule()];
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const makeEntityClass = (edgeDeletionBehavior: EntityEdgeDeletionBehavior) => {
class CategoryEntity extends Entity<CategoryFields, string, TestViewerContext> {
static getCompanionDefinition(): EntityCompanionDefinition<
CategoryFields,
string,
TestViewerContext,
CategoryEntity,
CategoryPrivacyPolicy
> {
return categoryEntityCompanion;
}
}
const categoryEntityConfiguration = new EntityConfiguration<CategoryFields>({
idField: 'id',
tableName: 'categories',
getInboundEdges: () => [CategoryEntity],
schema: {
id: new UUIDField({
columnName: 'id',
cache: true,
}),
parent_category_id: new UUIDField({
columnName: 'parent_category_id',
cache: true,
association: {
getAssociatedEntityClass: () => CategoryEntity,
edgeDeletionBehavior,
},
}),
},
databaseAdapterFlavor: DatabaseAdapterFlavor.POSTGRES,
cacheAdapterFlavor: CacheAdapterFlavor.REDIS,
});
const categoryEntityCompanion = new EntityCompanionDefinition({
entityClass: CategoryEntity,
entityConfiguration: categoryEntityConfiguration,
privacyPolicyClass: CategoryPrivacyPolicy,
});
return {
CategoryEntity,
};
};
describe('EntityEdgeDeletionBehavior.CASCADE_DELETE', () => {
it('deletes', async () => {
const { CategoryEntity } = makeEntityClass(EntityEdgeDeletionBehavior.CASCADE_DELETE);
const companionProvider = createUnitTestEntityCompanionProvider();
const viewerContext = new TestViewerContext(companionProvider);
const parentCategory = await CategoryEntity.creator(viewerContext).enforceCreateAsync();
const subCategory = await CategoryEntity.creator(viewerContext)
.setField('parent_category_id', parentCategory.getID())
.enforceCreateAsync();
const subSubCategory = await CategoryEntity.creator(viewerContext)
.setField('parent_category_id', subCategory.getID())
.enforceCreateAsync();
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parentCategory.getID())
).resolves.not.toBeNull();
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(subCategory.getID())
).resolves.not.toBeNull();
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(subSubCategory.getID())
).resolves.not.toBeNull();
await CategoryEntity.enforceDeleteAsync(parentCategory);
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parentCategory.getID())
).resolves.toBeNull();
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(subCategory.getID())
).resolves.toBeNull();
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(subSubCategory.getID())
).resolves.toBeNull();
});
it('handles cycles', async () => {
const { CategoryEntity } = makeEntityClass(EntityEdgeDeletionBehavior.CASCADE_DELETE);
const companionProvider = createUnitTestEntityCompanionProvider();
const viewerContext = new TestViewerContext(companionProvider);
const categoryA = await CategoryEntity.creator(viewerContext).enforceCreateAsync();
const categoryB = await CategoryEntity.creator(viewerContext)
.setField('parent_category_id', categoryA.getID())
.enforceCreateAsync();
await CategoryEntity.updater(categoryA)
.setField('parent_category_id', categoryB.getID())
.enforceUpdateAsync();
await CategoryEntity.enforceDeleteAsync(categoryA);
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(categoryA.getID())
).resolves.toBeNull();
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(categoryB.getID())
).resolves.toBeNull();
});
});
describe('EntityEdgeDeletionBehavior.SET_NULL', () => {
it('sets null', async () => {
const { CategoryEntity } = makeEntityClass(EntityEdgeDeletionBehavior.SET_NULL);
const companionProvider = createUnitTestEntityCompanionProvider();
const viewerContext = new TestViewerContext(companionProvider);
const parentCategory = await CategoryEntity.creator(viewerContext).enforceCreateAsync();
const subCategory = await CategoryEntity.creator(viewerContext)
.setField('parent_category_id', parentCategory.getID())
.enforceCreateAsync();
const subSubCategory = await CategoryEntity.creator(viewerContext)
.setField('parent_category_id', subCategory.getID())
.enforceCreateAsync();
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parentCategory.getID())
).resolves.not.toBeNull();
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(subCategory.getID())
).resolves.not.toBeNull();
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(subSubCategory.getID())
).resolves.not.toBeNull();
await CategoryEntity.enforceDeleteAsync(parentCategory);
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parentCategory.getID())
).resolves.toBeNull();
const loadedSubCategory = await CategoryEntity.loader(viewerContext)
.enforcing()
.loadByIDAsync(subCategory.getID());
expect(loadedSubCategory.getField('parent_category_id')).toBeNull();
const loadedSubSubCategory = await CategoryEntity.loader(viewerContext)
.enforcing()
.loadByIDAsync(subSubCategory.getID());
expect(loadedSubSubCategory.getField('parent_category_id')).not.toBeNull();
});
it('handles cycles', async () => {
const { CategoryEntity } = makeEntityClass(EntityEdgeDeletionBehavior.SET_NULL);
const companionProvider = createUnitTestEntityCompanionProvider();
const viewerContext = new TestViewerContext(companionProvider);
const categoryA = await CategoryEntity.creator(viewerContext).enforceCreateAsync();
const categoryB = await CategoryEntity.creator(viewerContext)
.setField('parent_category_id', categoryA.getID())
.enforceCreateAsync();
await CategoryEntity.updater(categoryA)
.setField('parent_category_id', categoryB.getID())
.enforceUpdateAsync();
await CategoryEntity.enforceDeleteAsync(categoryA);
const loadedCategoryB = await CategoryEntity.loader(viewerContext)
.enforcing()
.loadByIDAsync(categoryB.getID());
expect(loadedCategoryB.getField('parent_category_id')).toBeNull();
});
});
describe('EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE', () => {
it('invalidates the cache', async () => {
const { CategoryEntity } = makeEntityClass(
EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE
);
const companionProvider = createUnitTestEntityCompanionProvider();
const viewerContext = new TestViewerContext(companionProvider);
const parentCategory = await CategoryEntity.creator(viewerContext).enforceCreateAsync();
const subCategory = await CategoryEntity.creator(viewerContext)
.setField('parent_category_id', parentCategory.getID())
.enforceCreateAsync();
const subSubCategory = await CategoryEntity.creator(viewerContext)
.setField('parent_category_id', subCategory.getID())
.enforceCreateAsync();
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parentCategory.getID())
).resolves.not.toBeNull();
await expect(
CategoryEntity.loader(viewerContext)
.enforcing()
.loadByFieldEqualingAsync('parent_category_id', parentCategory.getID())
).resolves.not.toBeNull();
await expect(
CategoryEntity.loader(viewerContext)
.enforcing()
.loadByFieldEqualingAsync('parent_category_id', subCategory.getID())
).resolves.not.toBeNull();
const categoryCacheAdapter = viewerContext.getViewerScopedEntityCompanionForClass(
CategoryEntity
)['entityCompanion']['tableDataCoordinator'][
'cacheAdapter'
] as InMemoryFullCacheStubCacheAdapter<CategoryFields>;
const subCategoryCachedBefore = await categoryCacheAdapter.loadManyAsync('parent_category_id', [
parentCategory.getID(),
]);
expect(subCategoryCachedBefore.get(parentCategory.getID())?.status).toEqual(CacheStatus.HIT);
const subSubCategoryCachedBefore = await categoryCacheAdapter.loadManyAsync(
'parent_category_id',
[subCategory.getID()]
);
expect(subSubCategoryCachedBefore.get(subCategory.getID())?.status).toEqual(CacheStatus.HIT);
await CategoryEntity.enforceDeleteAsync(parentCategory);
const subCategoryCachedAfter = await categoryCacheAdapter.loadManyAsync('parent_category_id', [
parentCategory.getID(),
]);
expect(subCategoryCachedAfter.get(parentCategory.getID())?.status).toEqual(CacheStatus.MISS);
const subSubCategoryCachedAfter = await categoryCacheAdapter.loadManyAsync(
'parent_category_id',
[subCategory.getID()]
);
expect(subSubCategoryCachedAfter.get(subCategory.getID())?.status).toEqual(CacheStatus.MISS);
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parentCategory.getID())
).resolves.toBeNull();
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(subCategory.getID())
).resolves.not.toBeNull();
await expect(
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(subSubCategory.getID())
).resolves.not.toBeNull();
});
it('handles cycles', async () => {
const { CategoryEntity } = makeEntityClass(
EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE
);
const companionProvider = createUnitTestEntityCompanionProvider();
const viewerContext = new TestViewerContext(companionProvider);
const categoryA = await CategoryEntity.creator(viewerContext).enforceCreateAsync();
const categoryB = await CategoryEntity.creator(viewerContext)
.setField('parent_category_id', categoryA.getID())
.enforceCreateAsync();
await CategoryEntity.updater(categoryA)
.setField('parent_category_id', categoryB.getID())
.enforceUpdateAsync();
await expect(
CategoryEntity.loader(viewerContext)
.enforcing()
.loadByFieldEqualingAsync('parent_category_id', categoryA.getID())
).resolves.not.toBeNull();
await expect(
CategoryEntity.loader(viewerContext)
.enforcing()
.loadByFieldEqualingAsync('parent_category_id', categoryB.getID())
).resolves.not.toBeNull();
const categoryCacheAdapter = viewerContext.getViewerScopedEntityCompanionForClass(
CategoryEntity
)['entityCompanion']['tableDataCoordinator'][
'cacheAdapter'
] as InMemoryFullCacheStubCacheAdapter<CategoryFields>;
const categoriesCachedBefore = await categoryCacheAdapter.loadManyAsync('parent_category_id', [
categoryA.getID(),
categoryB.getID(),
]);
expect(categoriesCachedBefore.get(categoryA.getID())?.status).toEqual(CacheStatus.HIT);
expect(categoriesCachedBefore.get(categoryB.getID())?.status).toEqual(CacheStatus.HIT);
await CategoryEntity.enforceDeleteAsync(categoryA);
const categoriesCachedAfter = await categoryCacheAdapter.loadManyAsync('parent_category_id', [
categoryA.getID(),
categoryB.getID(),
]);
expect(categoriesCachedAfter.get(categoryA.getID())?.status).toEqual(CacheStatus.MISS);
expect(categoriesCachedAfter.get(categoryB.getID())?.status).toEqual(CacheStatus.MISS);
});
});
@@ -6,6 +6,7 @@ import { EntityQueryContext } from '../EntityQueryContext';
import ReadonlyEntity from '../ReadonlyEntity';
import ViewerContext from '../ViewerContext';
import SimpleTestEntity from '../testfixtures/SimpleTestEntity';
import TestEntity from '../testfixtures/TestEntity';
import { createUnitTestEntityCompanionProvider } from '../utils/testing/createUnitTestEntityCompanionProvider';
describe(ReadonlyEntity, () => {
@@ -31,6 +32,43 @@ describe(ReadonlyEntity, () => {
});
});
describe('getUniqueIdentifier', () => {
it('returns a different value for two different entities of the same type', () => {
const viewerContext = instance(mock(ViewerContext));
const testEntity = new SimpleTestEntity(viewerContext, {
id: '1',
});
const testEntity2 = new SimpleTestEntity(viewerContext, {
id: '2',
});
expect(testEntity.getUniqueIdentifier()).not.toEqual(testEntity2.getUniqueIdentifier());
});
it('returns the same value even if different viewer context', () => {
const viewerContext = instance(mock(ViewerContext));
const viewerContext2 = instance(mock(ViewerContext));
const data = { id: '1' };
const testEntity = new SimpleTestEntity(viewerContext, data);
const testEntity2 = new SimpleTestEntity(viewerContext2, data);
expect(testEntity.getUniqueIdentifier()).toEqual(testEntity2.getUniqueIdentifier());
});
it('returns a different value for different entities even if same ID', () => {
const viewerContext = instance(mock(ViewerContext));
const data = { id: '1' };
const testEntity = new SimpleTestEntity(viewerContext, data);
const testEntity2 = new TestEntity(viewerContext, {
customIdField: '1',
testIndexedField: '2',
stringField: '3',
numberField: 4,
dateField: new Date(),
nullableField: null,
});
expect(testEntity.getUniqueIdentifier()).not.toEqual(testEntity2.getUniqueIdentifier());
});
});
it('cannot be created without an ID', () => {
const viewerContext = instance(mock(ViewerContext));
const dataWithoutID = {};
@@ -74,7 +112,7 @@ describe(ReadonlyEntity, () => {
it('creates a new regular query context', () => {
const companionProvider = createUnitTestEntityCompanionProvider();
const viewerContext = new ViewerContext(companionProvider);
const queryContext = SimpleTestEntity.getRegularEntityQueryContext(viewerContext);
const queryContext = SimpleTestEntity.getQueryContext(viewerContext);
expect(queryContext).toBeInstanceOf(EntityQueryContext);
expect(queryContext.isInTransaction()).toBe(false);
});
@@ -8,6 +8,7 @@ import EntityConfiguration from '../../EntityConfiguration';
import { UUIDField, EnumField, StringField } from '../../EntityFields';
import EntityPrivacyPolicy from '../../EntityPrivacyPolicy';
import ViewerContext from '../../ViewerContext';
import { successfulResults, failedResults } from '../../entityUtils';
import AlwaysAllowPrivacyPolicyRule from '../../rules/AlwaysAllowPrivacyPolicyRule';
import { createUnitTestEntityCompanionProvider } from '../../utils/testing/createUnitTestEntityCompanionProvider';
@@ -18,11 +19,13 @@ describe('Two entities backed by the same table', () => {
const one = await OneTestEntity.creator(viewerContext)
.setField('entity_type', EntityType.ONE)
.setField('common_other_field', 'wat')
.enforceCreateAsync();
const two = await TwoTestEntity.creator(viewerContext)
.setField('entity_type', EntityType.TWO)
.setField('other_field', 'blah')
.setField('common_other_field', 'wat')
.enforceCreateAsync();
expect(one).toBeInstanceOf(OneTestEntity);
@@ -31,9 +34,42 @@ describe('Two entities backed by the same table', () => {
await expect(
TwoTestEntity.loader(viewerContext).enforcing().loadByIDAsync(one.getID())
).rejects.toThrowError('TwoTestEntity must be instantiated with two data');
await expect(
OneTestEntity.loader(viewerContext).enforcing().loadByIDAsync(two.getID())
).rejects.toThrowError('OneTestEntity must be instantiated with one data');
const manyResults = await OneTestEntity.loader(viewerContext).loadManyByFieldEqualingAsync(
'common_other_field',
'wat'
);
const successfulManyResults = successfulResults(manyResults);
const failedManyResults = failedResults(manyResults);
expect(successfulManyResults).toHaveLength(1);
expect(failedManyResults).toHaveLength(1);
expect(successfulManyResults[0].enforceValue().getID()).toEqual(one.getID());
expect(failedManyResults[0].enforceError().message).toEqual(
'OneTestEntity must be instantiated with one data'
);
const fieldEqualityConjunctionResults = await OneTestEntity.loader(
viewerContext
).loadManyByFieldEqualityConjunctionAsync([
{
fieldName: 'common_other_field',
fieldValue: 'wat',
},
]);
const successfulfieldEqualityConjunctionResultsResults = successfulResults(
fieldEqualityConjunctionResults
);
const failedfieldEqualityConjunctionResultsResults = failedResults(
fieldEqualityConjunctionResults
);
expect(successfulfieldEqualityConjunctionResultsResults).toHaveLength(1);
expect(failedfieldEqualityConjunctionResultsResults).toHaveLength(1);
});
});
@@ -45,11 +81,12 @@ enum EntityType {
interface TestFields {
id: string;
other_field: string;
common_other_field: string;
entity_type: EntityType;
}
type OneTestFields = 'id' | 'entity_type';
type TwoTestFields = 'id' | 'other_field' | 'entity_type';
type OneTestFields = 'id' | 'entity_type' | 'common_other_field';
type TwoTestFields = 'id' | 'other_field' | 'entity_type' | 'common_other_field';
const testEntityConfiguration = new EntityConfiguration<TestFields>({
idField: 'id',
@@ -62,6 +99,9 @@ const testEntityConfiguration = new EntityConfiguration<TestFields>({
other_field: new StringField({
columnName: 'other_field',
}),
common_other_field: new StringField({
columnName: 'common_other_field',
}),
entity_type: new EnumField({
columnName: 'entity_type',
}),
@@ -121,12 +161,12 @@ const oneTestEntityCompanion = new EntityCompanionDefinition({
entityClass: OneTestEntity,
entityConfiguration: testEntityConfiguration,
privacyPolicyClass: TestEntityPrivacyPolicy,
entitySelectedFields: ['id', 'entity_type'],
entitySelectedFields: ['id', 'entity_type', 'common_other_field'],
});
const twoTestEntityCompanion = new EntityCompanionDefinition({
entityClass: TwoTestEntity,
entityConfiguration: testEntityConfiguration,
privacyPolicyClass: TestEntityPrivacyPolicy,
entitySelectedFields: ['id', 'other_field', 'entity_type'],
entitySelectedFields: ['id', 'other_field', 'common_other_field', 'entity_type'],
});
@@ -6,6 +6,7 @@ import {
failedResults,
successfulResultsFilterMap,
failedResultsFilterMap,
pick,
} from '../entityUtils';
describe(enforceResultsAsync, () => {
@@ -42,39 +43,57 @@ describe(failedResults, () => {
});
describe(successfulResultsFilterMap, () => {
const result1 = result(1);
const result2 = result(new Error('hello'));
const result3 = result(1);
const allResults = new Map(
Object.entries({
a: result1,
b: result2,
c: result3,
})
);
it('filters out failed results', () => {
const result1 = result(1);
const result2 = result(new Error('hello'));
const result3 = result(1);
const allResults = new Map(
Object.entries({
a: result1,
b: result2,
c: result3,
})
);
const resultingMap = successfulResultsFilterMap(allResults);
const resultingMap = successfulResultsFilterMap(allResults);
expect(resultingMap.get('a')).toEqual(result1);
expect(resultingMap.get('b')).toBeUndefined();
expect(resultingMap.get('c')).toEqual(result3);
expect(resultingMap.get('a')).toEqual(result1);
expect(resultingMap.get('b')).toBeUndefined();
expect(resultingMap.get('c')).toEqual(result3);
});
});
describe(failedResultsFilterMap, () => {
const result1 = result(1);
const result2 = result(new Error('hello'));
const result3 = result(1);
const allResults = new Map(
Object.entries({
a: result1,
b: result2,
c: result3,
})
);
it('filters out successful results', () => {
const result1 = result(1);
const result2 = result(new Error('hello'));
const result3 = result(1);
const allResults = new Map(
Object.entries({
a: result1,
b: result2,
c: result3,
})
);
const resultingMap = failedResultsFilterMap(allResults);
const resultingMap = failedResultsFilterMap(allResults);
expect(resultingMap.get('a')).toBeUndefined();
expect(resultingMap.get('b')).toEqual(result2);
expect(resultingMap.get('c')).toBeUndefined();
expect(resultingMap.get('a')).toBeUndefined();
expect(resultingMap.get('b')).toEqual(result2);
expect(resultingMap.get('c')).toBeUndefined();
});
});
describe(pick, () => {
it('picks specified keys', () => {
const object = {
a: 1,
b: 2,
c: 3,
};
expect(pick(object, ['a', 'b'])).toEqual({
a: 1,
b: 2,
});
});
});
+7
View File
@@ -93,3 +93,10 @@ export const partitionErrors = <T>(valuesAndErrors: (T | Error)[]): [T[], Error[
const isError = <T>(value: T | Error): value is Error => {
return value instanceof Error;
};
export const pick = <T extends object, U extends keyof T>(object: T, props: U[]): Pick<T, U> => {
const propsSet = new Set(props);
return Object.fromEntries(
Object.entries(object).filter((entry) => propsSet.has(entry[0] as any))
) as any;
};
+4 -1
View File
@@ -16,13 +16,16 @@ export * from './EntityFields';
export { default as EntityLoader } from './EntityLoader';
export { default as EntityLoaderFactory } from './EntityLoaderFactory';
export * from './EntityMutator';
export { default as EntityMutationValidator } from './EntityMutationValidator';
export * from './EntityMutationTriggerConfiguration';
export { default as EntityMutationTriggerConfiguration } from './EntityMutationTriggerConfiguration';
export { default as EntityMutatorFactory } from './EntityMutatorFactory';
export { default as EntityPrivacyPolicy } from './EntityPrivacyPolicy';
export * from './EntityPrivacyPolicy';
export * from './EntityQueryContext';
export { default as IEntityCacheAdapterProvider } from './IEntityCacheAdapterProvider';
export { default as IEntityDatabaseAdapterProvider } from './IEntityDatabaseAdapterProvider';
export { default as IEntityQueryContextProvider } from './IEntityQueryContextProvider';
export { default as EntityQueryContextProvider } from './EntityQueryContextProvider';
export { default as ReadonlyEntity } from './ReadonlyEntity';
export { default as ViewerContext } from './ViewerContext';
export { default as ViewerScopedEntityCompanion } from './ViewerScopedEntityCompanion';
+119 -23
View File
@@ -4,8 +4,8 @@ import EntityDatabaseAdapter, {
FieldEqualityCondition,
QuerySelectionModifiers,
} from '../EntityDatabaseAdapter';
import { EntityQueryContext } from '../EntityQueryContext';
import IEntityQueryContextProvider from '../IEntityQueryContextProvider';
import { EntityQueryContext, EntityTransactionalQueryContext } from '../EntityQueryContext';
import EntityQueryContextProvider from '../EntityQueryContextProvider';
import { partitionErrors } from '../entityUtils';
import {
timeAndLogLoadEventAsync,
@@ -15,6 +15,13 @@ import IEntityMetricsAdapter, { EntityMetricsLoadType } from '../metrics/IEntity
import { computeIfAbsent, zipToMap } from '../utils/collections/maps';
import ReadThroughEntityCache from './ReadThroughEntityCache';
type FieldDataLoader<TFields> = DataLoader<
NonNullable<TFields[keyof TFields]>,
readonly Readonly<TFields>[]
>;
type FieldDataLoadersMap<TFields> = Map<keyof TFields, FieldDataLoader<TFields>>;
/**
* A data manager is responsible for orchestrating multiple sources of entity
* data including local caches, {@link EntityCacheAdapter}, and {@link EntityDatabaseAdapter}.
@@ -22,22 +29,25 @@ import ReadThroughEntityCache from './ReadThroughEntityCache';
* It is also responsible for invalidating all sources of data when mutated using {@link EntityMutator}.
*/
export default class EntityDataManager<TFields> {
private readonly fieldDataLoaders: Map<
keyof TFields,
DataLoader<NonNullable<TFields[keyof TFields]>, readonly Readonly<TFields>[]>
private readonly regularFieldDataLoaders: FieldDataLoadersMap<TFields> = new Map();
private readonly transactionalFieldDataLoaders: Map<
string,
FieldDataLoadersMap<TFields>
> = new Map();
constructor(
private readonly databaseAdapter: EntityDatabaseAdapter<TFields>,
private readonly entityCache: ReadThroughEntityCache<TFields>,
private readonly queryContextProvider: IEntityQueryContextProvider,
private readonly metricsAdapter: IEntityMetricsAdapter
private readonly queryContextProvider: EntityQueryContextProvider,
private readonly metricsAdapter: IEntityMetricsAdapter,
private readonly entityClassName: string
) {}
private getFieldDataLoaderForFieldName<N extends keyof TFields>(
private getRegularFieldDataLoderForFieldName<N extends keyof TFields>(
fieldName: N
): DataLoader<NonNullable<TFields[N]>, readonly Readonly<TFields>[]> {
return computeIfAbsent(this.fieldDataLoaders, fieldName, () => {
): FieldDataLoader<TFields> {
return computeIfAbsent(this.regularFieldDataLoaders, fieldName, () => {
return new DataLoader(
async (
fieldValues: readonly NonNullable<TFields[N]>[]
@@ -52,18 +62,62 @@ export default class EntityDataManager<TFields> {
});
}
private getTransactionalFieldDataLoaderForFieldName<N extends keyof TFields>(
queryContext: EntityTransactionalQueryContext,
fieldName: N
): FieldDataLoader<TFields> {
const fieldDataLoaderMap = computeIfAbsent(
this.transactionalFieldDataLoaders,
queryContext.transactionID,
() => new Map<keyof TFields, FieldDataLoader<TFields>>()
);
return computeIfAbsent(fieldDataLoaderMap, fieldName, () => {
return new DataLoader(
async (
fieldValues: readonly NonNullable<TFields[N]>[]
): Promise<readonly (readonly TFields[])[]> => {
const objectMap = await this.loadManyForTransactionalDataLoaderByFieldEqualingAsync(
fieldName,
fieldValues,
queryContext
);
return fieldValues.map((fv) => objectMap.get(fv) ?? []);
}
);
});
}
private async loadManyForTransactionalDataLoaderByFieldEqualingAsync<N extends keyof TFields>(
fieldName: N,
fieldValues: readonly NonNullable<TFields[N]>[],
queryContext: EntityTransactionalQueryContext
): Promise<ReadonlyMap<NonNullable<TFields[N]>, readonly Readonly<TFields>[]>> {
this.metricsAdapter.incrementDataManagerDatabaseLoadCount({
fieldValueCount: fieldValues.length,
entityClassName: this.entityClassName,
});
return await this.databaseAdapter.fetchManyWhereAsync(queryContext, fieldName, fieldValues);
}
private async loadManyForDataLoaderByFieldEqualingAsync<N extends keyof TFields>(
fieldName: N,
fieldValues: readonly NonNullable<TFields[N]>[]
): Promise<ReadonlyMap<NonNullable<TFields[N]>, readonly Readonly<TFields>[]>> {
this.metricsAdapter.incrementDataManagerCacheLoadCount(fieldValues.length);
this.metricsAdapter.incrementDataManagerCacheLoadCount({
fieldValueCount: fieldValues.length,
entityClassName: this.entityClassName,
});
return await this.entityCache.readManyThroughAsync(
fieldName,
fieldValues,
async (fetcherValues) => {
this.metricsAdapter.incrementDataManagerDatabaseLoadCount(fieldValues.length);
async (fetcherValues: readonly NonNullable<TFields[N]>[]) => {
this.metricsAdapter.incrementDataManagerDatabaseLoadCount({
fieldValueCount: fieldValues.length,
entityClassName: this.entityClassName,
});
return await this.databaseAdapter.fetchManyWhereAsync(
this.queryContextProvider.getRegularEntityQueryContext(),
this.queryContextProvider.getQueryContext(),
fieldName,
fetcherValues
);
@@ -86,7 +140,8 @@ export default class EntityDataManager<TFields> {
): Promise<ReadonlyMap<NonNullable<TFields[N]>, readonly Readonly<TFields>[]>> {
return await timeAndLogLoadMapEventAsync(
this.metricsAdapter,
EntityMetricsLoadType.LOAD_MANY
EntityMetricsLoadType.LOAD_MANY,
this.entityClassName
)(this.loadManyByFieldEqualingInternalAsync(queryContext, fieldName, fieldValues));
}
@@ -95,13 +150,22 @@ export default class EntityDataManager<TFields> {
fieldName: N,
fieldValues: readonly NonNullable<TFields[N]>[]
): Promise<ReadonlyMap<NonNullable<TFields[N]>, readonly Readonly<TFields>[]>> {
// don't cache when in transaction, as rollbacks complicate things significantly
if (queryContext.isInTransaction()) {
return await this.databaseAdapter.fetchManyWhereAsync(queryContext, fieldName, fieldValues);
const nullOrUndefinedValueIndex = fieldValues.findIndex(
(value) => value === null || value === undefined
);
if (nullOrUndefinedValueIndex >= 0) {
throw new Error(
`Invalid load: ${this.entityClassName} (${fieldName} = ${fieldValues[nullOrUndefinedValueIndex]})`
);
}
this.metricsAdapter.incrementDataManagerDataloaderLoadCount(fieldValues.length);
const dataLoader = this.getFieldDataLoaderForFieldName(fieldName);
this.metricsAdapter.incrementDataManagerDataloaderLoadCount({
fieldValueCount: fieldValues.length,
entityClassName: this.entityClassName,
});
const dataLoader = queryContext.isInTransaction()
? this.getTransactionalFieldDataLoaderForFieldName(queryContext, fieldName)
: this.getRegularFieldDataLoderForFieldName(fieldName);
const results = await dataLoader.loadMany(fieldValues);
const [values, errors] = partitionErrors(results);
if (errors.length > 0) {
@@ -127,7 +191,8 @@ export default class EntityDataManager<TFields> {
): Promise<readonly Readonly<TFields>[]> {
return await timeAndLogLoadEventAsync(
this.metricsAdapter,
EntityMetricsLoadType.LOAD_MANY_EQUALITY_CONJUNCTION
EntityMetricsLoadType.LOAD_MANY_EQUALITY_CONJUNCTION,
this.entityClassName
)(
this.databaseAdapter.fetchManyByFieldEqualityConjunctionAsync(
queryContext,
@@ -154,7 +219,8 @@ export default class EntityDataManager<TFields> {
): Promise<readonly Readonly<TFields>[]> {
return await timeAndLogLoadEventAsync(
this.metricsAdapter,
EntityMetricsLoadType.LOAD_MANY_RAW
EntityMetricsLoadType.LOAD_MANY_RAW,
this.entityClassName
)(
this.databaseAdapter.fetchManyByRawWhereClauseAsync(
queryContext,
@@ -170,7 +236,20 @@ export default class EntityDataManager<TFields> {
fieldValues: readonly NonNullable<TFields[N]>[]
): Promise<void> {
await this.entityCache.invalidateManyAsync(fieldName, fieldValues);
const dataLoader = this.getFieldDataLoaderForFieldName(fieldName);
const dataLoader = this.getRegularFieldDataLoderForFieldName(fieldName);
fieldValues.forEach((fieldValue) => dataLoader.clear(fieldValue));
}
private async invalidateManyByFieldEqualingTransactionalAsync<N extends keyof TFields>(
queryContext: EntityQueryContext,
fieldName: N,
fieldValues: readonly NonNullable<TFields[N]>[]
): Promise<void> {
if (!queryContext.isInTransaction()) {
return;
}
const dataLoader = this.getTransactionalFieldDataLoaderForFieldName(queryContext, fieldName);
fieldValues.forEach((fieldValue) => dataLoader.clear(fieldValue));
}
@@ -193,4 +272,21 @@ export default class EntityDataManager<TFields> {
})
);
}
async invalidateObjectFieldsTransactionalAsync(
queryContext: EntityQueryContext,
objectFields: Readonly<TFields>
): Promise<void> {
const keys = Object.keys(objectFields) as (keyof TFields)[];
await Promise.all(
keys.map(async (fieldName: keyof TFields) => {
const value = objectFields[fieldName];
if (value !== undefined) {
await this.invalidateManyByFieldEqualingTransactionalAsync(queryContext, fieldName, [
value as NonNullable<TFields[keyof TFields]>,
]);
}
})
);
}
}
@@ -1,9 +1,9 @@
import EntityCacheAdapter from '../EntityCacheAdapter';
import EntityConfiguration from '../EntityConfiguration';
import EntityDatabaseAdapter from '../EntityDatabaseAdapter';
import EntityQueryContextProvider from '../EntityQueryContextProvider';
import IEntityCacheAdapterProvider from '../IEntityCacheAdapterProvider';
import IEntityDatabaseAdapterProvider from '../IEntityDatabaseAdapterProvider';
import IEntityQueryContextProvider from '../IEntityQueryContextProvider';
import IEntityMetricsAdapter from '../metrics/IEntityMetricsAdapter';
import EntityDataManager from './EntityDataManager';
import ReadThroughEntityCache from './ReadThroughEntityCache';
@@ -22,8 +22,9 @@ export default class EntityTableDataCoordinator<TFields> {
readonly entityConfiguration: EntityConfiguration<TFields>,
databaseAdapterProvider: IEntityDatabaseAdapterProvider,
cacheAdapterProvider: IEntityCacheAdapterProvider,
private readonly queryContextProvider: IEntityQueryContextProvider,
metricsAdapter: IEntityMetricsAdapter
private readonly queryContextProvider: EntityQueryContextProvider,
metricsAdapter: IEntityMetricsAdapter,
entityClassName: string
) {
this.databaseAdapter = databaseAdapterProvider.getDatabaseAdapter(entityConfiguration);
this.cacheAdapter = cacheAdapterProvider.getCacheAdapter(entityConfiguration);
@@ -31,11 +32,12 @@ export default class EntityTableDataCoordinator<TFields> {
this.databaseAdapter,
new ReadThroughEntityCache(entityConfiguration, this.cacheAdapter),
queryContextProvider,
metricsAdapter
metricsAdapter,
entityClassName
);
}
getQueryContextProvider(): IEntityQueryContextProvider {
getQueryContextProvider(): EntityQueryContextProvider {
return this.queryContextProvider;
}
}
@@ -9,12 +9,13 @@ import {
spy,
anyString,
resetCalls,
deepEqual,
} from 'ts-mockito';
import EntityDatabaseAdapter from '../../EntityDatabaseAdapter';
import IEntityMetricsAdapter, { EntityMetricsLoadType } from '../../metrics/IEntityMetricsAdapter';
import NoOpEntityMetricsAdapter from '../../metrics/NoOpEntityMetricsAdapter';
import { testEntityConfiguration, TestFields } from '../../testfixtures/TestEntity';
import TestEntity, { testEntityConfiguration, TestFields } from '../../testfixtures/TestEntity';
import {
NoCacheStubCacheAdapterProvider,
InMemoryFullCacheStubCacheAdapterProvider,
@@ -35,6 +36,7 @@ const getObjects = (): Map<string, TestFields[]> =>
stringField: 'hello',
numberField: 1,
dateField: new Date(),
nullableField: null,
},
{
customIdField: '2',
@@ -42,6 +44,7 @@ const getObjects = (): Map<string, TestFields[]> =>
stringField: 'hello',
numberField: 1,
dateField: new Date(),
nullableField: null,
},
{
customIdField: '3',
@@ -49,6 +52,7 @@ const getObjects = (): Map<string, TestFields[]> =>
stringField: 'world',
numberField: 1,
dateField: new Date(),
nullableField: null,
},
],
],
@@ -69,9 +73,10 @@ describe(EntityDataManager, () => {
databaseAdapter,
entityCache,
StubQueryContextProvider,
new NoOpEntityMetricsAdapter()
new NoOpEntityMetricsAdapter(),
TestEntity.name
);
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
const queryContext = StubQueryContextProvider.getQueryContext();
const dbSpy = jest.spyOn(databaseAdapter, 'fetchManyWhereAsync');
const cacheSpy = jest.spyOn(entityCache, 'readManyThroughAsync');
@@ -116,9 +121,10 @@ describe(EntityDataManager, () => {
databaseAdapter,
entityCache,
StubQueryContextProvider,
new NoOpEntityMetricsAdapter()
new NoOpEntityMetricsAdapter(),
TestEntity.name
);
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
const queryContext = StubQueryContextProvider.getQueryContext();
const dbSpy = jest.spyOn(databaseAdapter, 'fetchManyWhereAsync');
const cacheSpy = jest.spyOn(entityCache, 'readManyThroughAsync');
@@ -163,15 +169,17 @@ describe(EntityDataManager, () => {
databaseAdapter,
entityCache,
StubQueryContextProvider,
new NoOpEntityMetricsAdapter()
new NoOpEntityMetricsAdapter(),
TestEntity.name
);
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
const queryContext = StubQueryContextProvider.getQueryContext();
// use second data manager to ensure that cache is hit instead of data loader
const entityDataManager2 = new EntityDataManager(
databaseAdapter,
entityCache,
StubQueryContextProvider,
new NoOpEntityMetricsAdapter()
new NoOpEntityMetricsAdapter(),
TestEntity.name
);
const dbSpy = jest.spyOn(databaseAdapter, 'fetchManyWhereAsync');
@@ -205,9 +213,10 @@ describe(EntityDataManager, () => {
databaseAdapter,
entityCache,
StubQueryContextProvider,
new NoOpEntityMetricsAdapter()
new NoOpEntityMetricsAdapter(),
TestEntity.name
);
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
const queryContext = StubQueryContextProvider.getQueryContext();
const dbSpy = jest.spyOn(databaseAdapter, 'fetchManyWhereAsync');
const cacheSpy = jest.spyOn(entityCache, 'readManyThroughAsync');
@@ -240,9 +249,10 @@ describe(EntityDataManager, () => {
databaseAdapter,
entityCache,
StubQueryContextProvider,
new NoOpEntityMetricsAdapter()
new NoOpEntityMetricsAdapter(),
TestEntity.name
);
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
const queryContext = StubQueryContextProvider.getQueryContext();
const dbSpy = jest.spyOn(databaseAdapter, 'fetchManyWhereAsync');
const cacheSpy = jest.spyOn(entityCache, 'readManyThroughAsync');
@@ -283,9 +293,10 @@ describe(EntityDataManager, () => {
databaseAdapter,
entityCache,
StubQueryContextProvider,
new NoOpEntityMetricsAdapter()
new NoOpEntityMetricsAdapter(),
TestEntity.name
);
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
const queryContext = StubQueryContextProvider.getQueryContext();
const objectInQuestion = objects.get(testEntityConfiguration.tableName)![1];
@@ -321,9 +332,10 @@ describe(EntityDataManager, () => {
databaseAdapter,
entityCache,
StubQueryContextProvider,
new NoOpEntityMetricsAdapter()
new NoOpEntityMetricsAdapter(),
TestEntity.name
);
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
const queryContext = StubQueryContextProvider.getQueryContext();
const objectInQuestion = objects.get(testEntityConfiguration.tableName)![1];
@@ -359,7 +371,8 @@ describe(EntityDataManager, () => {
databaseAdapter,
entityCache,
StubQueryContextProvider,
new NoOpEntityMetricsAdapter()
new NoOpEntityMetricsAdapter(),
TestEntity.name
);
const dbSpy = jest.spyOn(databaseAdapter, 'fetchManyWhereAsync');
@@ -396,9 +409,10 @@ describe(EntityDataManager, () => {
databaseAdapter,
entityCache,
StubQueryContextProvider,
new NoOpEntityMetricsAdapter()
new NoOpEntityMetricsAdapter(),
TestEntity.name
);
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
const queryContext = StubQueryContextProvider.getQueryContext();
const dbSpy = jest.spyOn(databaseAdapter, 'fetchManyByFieldEqualityConjunctionAsync');
const cacheSpy = jest.spyOn(entityCache, 'readManyThroughAsync');
@@ -441,9 +455,10 @@ describe(EntityDataManager, () => {
databaseAdapter,
entityCache,
StubQueryContextProvider,
new NoOpEntityMetricsAdapter()
new NoOpEntityMetricsAdapter(),
TestEntity.name
);
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
const queryContext = StubQueryContextProvider.getQueryContext();
await expect(
entityDataManager.loadManyByFieldEqualingAsync(queryContext, 'customIdField', ['2'])
@@ -467,15 +482,17 @@ describe(EntityDataManager, () => {
databaseAdapter,
entityCache,
StubQueryContextProvider,
metricsAdapter
metricsAdapter,
TestEntity.name
);
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
const queryContext = StubQueryContextProvider.getQueryContext();
await entityDataManager.loadManyByFieldEqualingAsync(queryContext, 'customIdField', ['1']);
verify(
metricsAdapterMock.logDataManagerLoadEvent(
objectContaining({
type: EntityMetricsLoadType.LOAD_MANY,
entityClassName: TestEntity.name,
count: 1,
})
)
@@ -495,14 +512,36 @@ describe(EntityDataManager, () => {
metricsAdapterMock.logDataManagerLoadEvent(
objectContaining({
type: EntityMetricsLoadType.LOAD_MANY_EQUALITY_CONJUNCTION,
entityClassName: TestEntity.name,
count: 1,
})
)
).once();
verify(metricsAdapterMock.incrementDataManagerDataloaderLoadCount(1)).once();
verify(metricsAdapterMock.incrementDataManagerCacheLoadCount(1)).once();
verify(metricsAdapterMock.incrementDataManagerDatabaseLoadCount(1)).once();
verify(
metricsAdapterMock.incrementDataManagerDataloaderLoadCount(
deepEqual({
fieldValueCount: 1,
entityClassName: TestEntity.name,
})
)
).once();
verify(
metricsAdapterMock.incrementDataManagerCacheLoadCount(
deepEqual({
fieldValueCount: 1,
entityClassName: TestEntity.name,
})
)
).once();
verify(
metricsAdapterMock.incrementDataManagerDatabaseLoadCount(
deepEqual({
fieldValueCount: 1,
entityClassName: TestEntity.name,
})
)
).once();
resetCalls(metricsAdapterMock);
@@ -520,6 +559,7 @@ describe(EntityDataManager, () => {
metricsAdapterMock.logDataManagerLoadEvent(
objectContaining({
type: EntityMetricsLoadType.LOAD_MANY_RAW,
entityClassName: TestEntity.name,
count: 0,
})
)
@@ -529,4 +569,34 @@ describe(EntityDataManager, () => {
verify(metricsAdapterMock.incrementDataManagerCacheLoadCount(anyNumber())).never();
verify(metricsAdapterMock.incrementDataManagerDatabaseLoadCount(anyNumber())).never();
});
it('throws when a load-by value is null or undefined', async () => {
const objects = getObjects();
const dataStore = StubDatabaseAdapter.convertFieldObjectsToDataStore(
testEntityConfiguration,
objects
);
const databaseAdapter = new StubDatabaseAdapter<TestFields>(testEntityConfiguration, dataStore);
const cacheAdapterProvider = new NoCacheStubCacheAdapterProvider();
const cacheAdapter = cacheAdapterProvider.getCacheAdapter(testEntityConfiguration);
const entityCache = new ReadThroughEntityCache(testEntityConfiguration, cacheAdapter);
const entityDataManager = new EntityDataManager(
databaseAdapter,
entityCache,
StubQueryContextProvider,
new NoOpEntityMetricsAdapter(),
TestEntity.name
);
const queryContext = StubQueryContextProvider.getQueryContext();
await expect(
entityDataManager.loadManyByFieldEqualingAsync(queryContext, 'nullableField', [null as any])
).rejects.toThrowError('Invalid load: TestEntity (nullableField = null)');
await expect(
entityDataManager.loadManyByFieldEqualingAsync(queryContext, 'nullableField', [
undefined as any,
])
).rejects.toThrowError('Invalid load: TestEntity (nullableField = undefined)');
});
});
@@ -6,7 +6,8 @@ import IEntityMetricsAdapter, {
export const timeAndLogLoadEventAsync = (
metricsAdapter: IEntityMetricsAdapter,
loadType: EntityMetricsLoadType
loadType: EntityMetricsLoadType,
entityClassName: string
) => async <TFields>(promise: Promise<readonly Readonly<TFields>[]>) => {
const startTime = Date.now();
const result = await promise;
@@ -14,6 +15,7 @@ export const timeAndLogLoadEventAsync = (
metricsAdapter.logDataManagerLoadEvent({
type: loadType,
entityClassName,
duration: endTime - startTime,
count: result.length,
});
@@ -23,7 +25,8 @@ export const timeAndLogLoadEventAsync = (
export const timeAndLogLoadMapEventAsync = (
metricsAdapter: IEntityMetricsAdapter,
loadType: EntityMetricsLoadType
loadType: EntityMetricsLoadType,
entityClassName: string
) => async <TFields, N extends keyof TFields>(
promise: Promise<ReadonlyMap<NonNullable<TFields[N]>, readonly Readonly<TFields>[]>>
) => {
@@ -35,6 +38,7 @@ export const timeAndLogLoadMapEventAsync = (
metricsAdapter.logDataManagerLoadEvent({
type: loadType,
entityClassName,
duration: endTime - startTime,
count,
});
@@ -44,7 +48,8 @@ export const timeAndLogLoadMapEventAsync = (
export const timeAndLogMutationEventAsync = (
metricsAdapter: IEntityMetricsAdapter,
mutationType: EntityMetricsMutationType
mutationType: EntityMetricsMutationType,
entityClassName: string
) => async <T>(promise: Promise<T>) => {
const startTime = Date.now();
const result = await promise;
@@ -52,6 +57,7 @@ export const timeAndLogMutationEventAsync = (
metricsAdapter.logMutatorMutationEvent({
type: mutationType,
entityClassName,
duration: endTime - startTime,
});
@@ -6,6 +6,7 @@ export enum EntityMetricsLoadType {
export interface EntityMetricsLoadEvent {
type: EntityMetricsLoadType;
entityClassName: string;
duration: number;
count: number;
}
@@ -18,9 +19,15 @@ export enum EntityMetricsMutationType {
export interface EntityMetricsMutationEvent {
type: EntityMetricsMutationType;
entityClassName: string;
duration: number;
}
export interface IncrementLoadCountEvent {
fieldValueCount: number;
entityClassName: string;
}
/**
* An interface for gathering metrics about the Entity framework. Information about
* entity load and mutation operations is piped to an instance of this adapter.
@@ -43,7 +50,7 @@ export default interface IEntityMetricsAdapter {
* load methods (not equality conjunction or raw).
* @param fieldValueCount - count of field values being loaded for a field
*/
incrementDataManagerDataloaderLoadCount(fieldValueCount: number): void;
incrementDataManagerDataloaderLoadCount(incrementLoadCountEvent: IncrementLoadCountEvent): void;
/**
* Called when a cache load is initiated via the standard
@@ -51,7 +58,7 @@ export default interface IEntityMetricsAdapter {
* miss.
* @param fieldValueCount - count of field values being loaded for a field
*/
incrementDataManagerCacheLoadCount(fieldValueCount: number): void;
incrementDataManagerCacheLoadCount(incrementLoadCountEvent: IncrementLoadCountEvent): void;
/**
* Called when a database load is initiated via the standard
@@ -59,5 +66,5 @@ export default interface IEntityMetricsAdapter {
* miss or when fetching an uncacheable field.
* @param fieldValueCount - count of field values being loaded for a field
*/
incrementDataManagerDatabaseLoadCount(fieldValueCount: number): void;
incrementDataManagerDatabaseLoadCount(incrementLoadCountEvent: IncrementLoadCountEvent): void;
}
@@ -1,12 +1,15 @@
import IEntityMetricsAdapter, {
EntityMetricsLoadEvent,
EntityMetricsMutationEvent,
IncrementLoadCountEvent,
} from './IEntityMetricsAdapter';
export default class NoOpEntityMetricsAdapter implements IEntityMetricsAdapter {
logDataManagerLoadEvent(_loadEvent: EntityMetricsLoadEvent): void {}
logMutatorMutationEvent(_mutationEvent: EntityMetricsMutationEvent): void {}
incrementDataManagerDataloaderLoadCount(_fieldValueCount: number): void {}
incrementDataManagerCacheLoadCount(_fieldValueCount: number): void {}
incrementDataManagerDatabaseLoadCount(_fieldValueCount: number): void {}
incrementDataManagerDataloaderLoadCount(
_incrementLoadCountEvent: IncrementLoadCountEvent
): void {}
incrementDataManagerCacheLoadCount(_incrementLoadCountEvent: IncrementLoadCountEvent): void {}
incrementDataManagerDatabaseLoadCount(_incrementLoadCountEvent: IncrementLoadCountEvent): void {}
}
@@ -18,6 +18,7 @@ export type TestFields = {
stringField: string;
numberField: number;
dateField: Date;
nullableField: string | null;
};
export const testEntityConfiguration = new EntityConfiguration<TestFields>({
@@ -40,6 +41,9 @@ export const testEntityConfiguration = new EntityConfiguration<TestFields>({
dateField: new DateField({
columnName: 'date_field',
}),
nullableField: new StringField({
columnName: 'nullable_field',
}),
},
databaseAdapterFlavor: DatabaseAdapterFlavor.POSTGRES,
cacheAdapterFlavor: CacheAdapterFlavor.REDIS,
@@ -88,6 +92,7 @@ export default class TestEntity extends Entity<TestFields, string, ViewerContext
stringField: 'hello',
numberField: 1,
dateField: new Date(),
nullableField: null,
})
);
}
@@ -57,7 +57,7 @@ export class InMemoryFullCacheStubCacheAdapterProvider implements IEntityCacheAd
}
}
class InMemoryFullCacheStubCacheAdapter<TFields> extends EntityCacheAdapter<TFields> {
export class InMemoryFullCacheStubCacheAdapter<TFields> extends EntityCacheAdapter<TFields> {
constructor(
entityConfiguration: EntityConfiguration<TFields>,
readonly cache: Map<string, Readonly<object>>
@@ -118,6 +118,11 @@ class InMemoryFullCacheStubCacheAdapter<TFields> extends EntityCacheAdapter<TFie
}
private createCacheKey<N extends keyof TFields>(fieldName: N, fieldValue: TFields[N]): string {
return `${fieldName}:::${fieldValue}`;
return [
this.entityConfiguration.tableName,
`v${this.entityConfiguration.cacheKeyVersion}`,
fieldName as string,
String(fieldValue),
].join(':');
}
}
@@ -205,7 +205,9 @@ export default class StubDatabaseAdapter<T> extends EntityDatabaseAdapter<T> {
const objectIndex = objectCollection.findIndex((obj) => {
return obj[tableIdField] === id;
});
invariant(objectIndex >= 0, 'should exist');
if (objectIndex < 0) {
return 0;
}
objectCollection.splice(objectIndex, 1);
return 1;
}
@@ -1,19 +1,14 @@
import {
EntityNonTransactionalQueryContext,
EntityQueryContext,
EntityTransactionalQueryContext,
} from '../../EntityQueryContext';
import IEntityQueryContextProvider from '../../IEntityQueryContextProvider';
import EntityQueryContextProvider from '../../EntityQueryContextProvider';
class StubQueryContextProvider implements IEntityQueryContextProvider {
getRegularEntityQueryContext(): EntityQueryContext {
return new EntityNonTransactionalQueryContext({});
class StubQueryContextProvider extends EntityQueryContextProvider {
protected getQueryInterface(): any {
return {};
}
async runInTransactionAsync<T>(
transactionScope: (queryContext: EntityQueryContext) => Promise<T>
): Promise<T> {
return await transactionScope(new EntityTransactionalQueryContext({}));
protected createTransactionRunner<T>(): (
transactionScope: (queryInterface: any) => Promise<T>
) => Promise<T> {
return (transactionScope) => Promise.resolve(transactionScope({}));
}
}
@@ -1,7 +1,7 @@
import { instance, mock } from 'ts-mockito';
import { OrderByOrdering } from '../../../EntityDatabaseAdapter';
import { EntityNonTransactionalQueryContext } from '../../../EntityQueryContext';
import { EntityQueryContext } from '../../../EntityQueryContext';
import {
DateIDTestFields,
dateIDTestEntityConfiguration,
@@ -20,7 +20,7 @@ import StubDatabaseAdapter from '../StubDatabaseAdapter';
describe(StubDatabaseAdapter, () => {
describe('fetchManyWhereAsync', () => {
it('fetches many where', async () => {
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = instance(mock(EntityQueryContext));
const databaseAdapter = new StubDatabaseAdapter<TestFields>(
testEntityConfiguration,
StubDatabaseAdapter.convertFieldObjectsToDataStore(
@@ -35,6 +35,7 @@ describe(StubDatabaseAdapter, () => {
numberField: 5,
stringField: 'huh',
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'world',
@@ -42,6 +43,7 @@ describe(StubDatabaseAdapter, () => {
numberField: 3,
stringField: 'wat',
dateField: new Date(),
nullableField: null,
},
],
],
@@ -58,7 +60,7 @@ describe(StubDatabaseAdapter, () => {
describe('fetchManyByFieldEqualityConjunctionAsync', () => {
it('supports conjuntions and query modifiers', async () => {
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = instance(mock(EntityQueryContext));
const databaseAdapter = new StubDatabaseAdapter<TestFields>(
testEntityConfiguration,
StubDatabaseAdapter.convertFieldObjectsToDataStore(
@@ -73,6 +75,7 @@ describe(StubDatabaseAdapter, () => {
numberField: 3,
stringField: 'a',
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'world',
@@ -80,6 +83,7 @@ describe(StubDatabaseAdapter, () => {
numberField: 3,
stringField: 'b',
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'world',
@@ -87,6 +91,7 @@ describe(StubDatabaseAdapter, () => {
numberField: 3,
stringField: 'c',
dateField: new Date(),
nullableField: null,
},
],
],
@@ -123,7 +128,7 @@ describe(StubDatabaseAdapter, () => {
});
it('supports multiple order bys', async () => {
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = instance(mock(EntityQueryContext));
const databaseAdapter = new StubDatabaseAdapter<TestFields>(
testEntityConfiguration,
StubDatabaseAdapter.convertFieldObjectsToDataStore(
@@ -138,6 +143,7 @@ describe(StubDatabaseAdapter, () => {
numberField: 3,
stringField: 'a',
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'world',
@@ -145,6 +151,7 @@ describe(StubDatabaseAdapter, () => {
numberField: 3,
stringField: 'b',
dateField: new Date(),
nullableField: null,
},
{
customIdField: 'world',
@@ -152,6 +159,7 @@ describe(StubDatabaseAdapter, () => {
numberField: 3,
stringField: 'c',
dateField: new Date(),
nullableField: null,
},
],
],
@@ -188,7 +196,7 @@ describe(StubDatabaseAdapter, () => {
describe('fetchManyByRawWhereClauseAsync', () => {
it('throws because it is unsupported', async () => {
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = instance(mock(EntityQueryContext));
const databaseAdapter = new StubDatabaseAdapter<TestFields>(
testEntityConfiguration,
new Map()
@@ -201,7 +209,7 @@ describe(StubDatabaseAdapter, () => {
describe('insertAsync', () => {
it('inserts a record', async () => {
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = instance(mock(EntityQueryContext));
const databaseAdapter = new StubDatabaseAdapter<TestFields>(
testEntityConfiguration,
new Map()
@@ -221,7 +229,7 @@ describe(StubDatabaseAdapter, () => {
describe('updateAsync', () => {
it('updates a record', async () => {
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = instance(mock(EntityQueryContext));
const databaseAdapter = new StubDatabaseAdapter<TestFields>(
testEntityConfiguration,
StubDatabaseAdapter.convertFieldObjectsToDataStore(
@@ -236,6 +244,7 @@ describe(StubDatabaseAdapter, () => {
numberField: 3,
stringField: 'a',
dateField: new Date(),
nullableField: null,
},
],
],
@@ -254,7 +263,7 @@ describe(StubDatabaseAdapter, () => {
describe('deleteAsync', () => {
it('deletes an object', async () => {
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = instance(mock(EntityQueryContext));
const databaseAdapter = new StubDatabaseAdapter<TestFields>(
testEntityConfiguration,
StubDatabaseAdapter.convertFieldObjectsToDataStore(
@@ -269,6 +278,7 @@ describe(StubDatabaseAdapter, () => {
numberField: 3,
stringField: 'a',
dateField: new Date(),
nullableField: null,
},
],
],
@@ -285,7 +295,7 @@ describe(StubDatabaseAdapter, () => {
});
it('supports string and number IDs', async () => {
const queryContext = instance(mock(EntityNonTransactionalQueryContext));
const queryContext = instance(mock(EntityQueryContext));
const databaseAdapter1 = new StubDatabaseAdapter<SimpleTestFields>(
simpleTestEntityConfiguration,
new Map()
+7
View File
@@ -3,4 +3,11 @@ module.exports = {
testMatch: ['**/__integration-tests__/**/*-test.ts'],
coveragePathIgnorePatterns: ['testfixtures'],
coverageDirectory: 'coverage-integration',
globals: {
'ts-jest': {
diagnostics: {
warnOnly: true,
},
},
},
};
+7
View File
@@ -2,4 +2,11 @@ module.exports = {
preset: 'ts-jest',
testMatch: ['**/__tests__/**/*-test.ts'],
coveragePathIgnorePatterns: ['testfixtures'],
globals: {
'ts-jest': {
diagnostics: {
warnOnly: true,
},
},
},
};
+2 -2
View File
@@ -1,7 +1,7 @@
{
"compilerOptions": {
"target": "es2018",
"lib": ["es2018"],
"target": "es2019",
"lib": ["es2019"],
"module": "commonjs",
"sourceMap": true,
"moduleResolution": "node",
+1 -1
View File
@@ -8,7 +8,7 @@
"**/__integration-tests__/**/*.ts",
"**/testfixtures/**/*.ts"
],
"lernaExclude": ["@expo/entity-example"],
"lernaExclude": ["@expo/entity-example", "@expo/entity-full-integration-tests"],
"name": "Entity",
"readme": "README.md",
"excludeNotExported": true
+2231 -1452
View File
File diff suppressed because it is too large. Load diff