mirror of
https://github.com/expo/entity.git
synced 2026-11-15 17:32:07 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b580a218c0 | ||
|
|
547a1efcec | ||
|
|
fc4377d883 | ||
|
|
5744c51e6b | ||
|
|
fd6060cc84 | ||
|
|
a757867360 | ||
|
|
1224de79d5 | ||
|
|
7a77afc83e |
No files matched your search
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -3,6 +3,25 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [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)
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -4,5 +4,5 @@
|
||||
],
|
||||
"npmClient": "yarn",
|
||||
"useWorkspaces": true,
|
||||
"version": "0.5.2"
|
||||
"version": "0.6.0"
|
||||
}
|
||||
@@ -18,7 +18,6 @@
|
||||
"@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",
|
||||
|
||||
@@ -3,6 +3,14 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity-cache-adapter-redis",
|
||||
"version": "0.5.2",
|
||||
"version": "0.6.0",
|
||||
"description": "Redis cache adapter for @expo/entity",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -18,7 +18,7 @@
|
||||
"barrelsby": "barrelsby --directory src --location top --exclude tests__ --singleQuotes --exportDefault --delete"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
"node": ">=12"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
@@ -32,6 +32,6 @@
|
||||
"ioredis": "^4.16.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/entity": "^0.5.2"
|
||||
"@expo/entity": "^0.6.0"
|
||||
}
|
||||
}
|
||||
+8
-4
@@ -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,23 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity-database-adapter-knex",
|
||||
"version": "0.5.2",
|
||||
"version": "0.6.0",
|
||||
"description": "Knex database adapter for @expo/entity",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -18,7 +18,7 @@
|
||||
"barrelsby": "barrelsby --directory src --location top --exclude tests__ --singleQuotes --exportDefault --delete"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
"node": ">=12"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
@@ -32,6 +32,6 @@
|
||||
"knex": "^0.20.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/entity": "^0.5.2"
|
||||
"@expo/entity": "^0.6.0"
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,8 @@ import Knex from 'knex';
|
||||
export default class PostgresEntityQueryContextProvider implements IEntityQueryContextProvider {
|
||||
constructor(private readonly knexInstance: Knex) {}
|
||||
|
||||
getRegularEntityQueryContext(): EntityNonTransactionalQueryContext {
|
||||
return new EntityNonTransactionalQueryContext(this.knexInstance);
|
||||
getQueryContext(): EntityNonTransactionalQueryContext {
|
||||
return new EntityNonTransactionalQueryContext(this.knexInstance, this);
|
||||
}
|
||||
|
||||
async runInTransactionAsync<T>(
|
||||
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
import {
|
||||
EntityPrivacyPolicy,
|
||||
ViewerContext,
|
||||
AlwaysAllowPrivacyPolicyRule,
|
||||
Entity,
|
||||
EntityCompanionDefinition,
|
||||
EntityConfiguration,
|
||||
DatabaseAdapterFlavor,
|
||||
CacheAdapterFlavor,
|
||||
UUIDField,
|
||||
EntityEdgeDeletionBehavior,
|
||||
} from '@expo/entity';
|
||||
import Knex from 'knex';
|
||||
|
||||
import { createKnexIntegrationTestEntityCompanionProvider } from '../testfixtures/createKnexIntegrationTestEntityCompanionProvider';
|
||||
|
||||
interface ParentFields {
|
||||
id: string;
|
||||
}
|
||||
|
||||
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()];
|
||||
}
|
||||
|
||||
class ParentEntity extends Entity<ParentFields, string, ViewerContext> {
|
||||
static getCompanionDefinition(): EntityCompanionDefinition<
|
||||
ParentFields,
|
||||
string,
|
||||
ViewerContext,
|
||||
ParentEntity,
|
||||
TestEntityPrivacyPolicy
|
||||
> {
|
||||
return parentEntityCompanion;
|
||||
}
|
||||
}
|
||||
|
||||
class ChildEntity extends Entity<ChildFields, string, ViewerContext> {
|
||||
static getCompanionDefinition(): EntityCompanionDefinition<
|
||||
ChildFields,
|
||||
string,
|
||||
ViewerContext,
|
||||
ChildEntity,
|
||||
TestEntityPrivacyPolicy
|
||||
> {
|
||||
return childEntityCompanion;
|
||||
}
|
||||
}
|
||||
|
||||
const parentEntityConfiguration = new EntityConfiguration<ParentFields>({
|
||||
idField: 'id',
|
||||
tableName: 'parents',
|
||||
inboundEdges: [ChildEntity],
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: DatabaseAdapterFlavor.POSTGRES,
|
||||
cacheAdapterFlavor: CacheAdapterFlavor.REDIS,
|
||||
});
|
||||
|
||||
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: {
|
||||
associatedEntityClass: ParentEntity,
|
||||
edgeDeletionBehavior: EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE,
|
||||
},
|
||||
}),
|
||||
},
|
||||
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,
|
||||
});
|
||||
|
||||
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;
|
||||
|
||||
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,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await createOrTruncatePostgresTables(knexInstance);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await dropPostgresTable(knexInstance);
|
||||
knexInstance.destroy();
|
||||
});
|
||||
|
||||
describe('EntityEdgeDeletionBehavior.INVALIDATE_CACHE', () => {
|
||||
it('invalidates the cache', async () => {
|
||||
const viewerContext = new ViewerContext(
|
||||
createKnexIntegrationTestEntityCompanionProvider(knexInstance)
|
||||
);
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
import {
|
||||
EntityPrivacyPolicy,
|
||||
ViewerContext,
|
||||
AlwaysAllowPrivacyPolicyRule,
|
||||
Entity,
|
||||
EntityCompanionDefinition,
|
||||
EntityConfiguration,
|
||||
DatabaseAdapterFlavor,
|
||||
CacheAdapterFlavor,
|
||||
UUIDField,
|
||||
EntityEdgeDeletionBehavior,
|
||||
} from '@expo/entity';
|
||||
import Knex from 'knex';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import { createKnexIntegrationTestEntityCompanionProvider } from '../testfixtures/createKnexIntegrationTestEntityCompanionProvider';
|
||||
|
||||
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,
|
||||
inboundEdges: [OtherEntity],
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
parent_other_id: new UUIDField({
|
||||
columnName: 'parent_other_id',
|
||||
cache: true,
|
||||
association: {
|
||||
associatedEntityClass: 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,
|
||||
inboundEdges: [CategoryEntity],
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
parent_category_id: new UUIDField({
|
||||
columnName: 'parent_category_id',
|
||||
cache: true,
|
||||
association: {
|
||||
associatedEntityClass: 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;
|
||||
|
||||
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,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
knexInstance.destroy();
|
||||
});
|
||||
|
||||
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(
|
||||
createKnexIntegrationTestEntityCompanionProvider(knexInstance)
|
||||
);
|
||||
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
+221
@@ -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', () => {
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
-3
@@ -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,154 @@
|
||||
import {
|
||||
AlwaysAllowPrivacyPolicyRule,
|
||||
EntityPrivacyPolicy,
|
||||
ViewerContext,
|
||||
UUIDField,
|
||||
StringField,
|
||||
EntityConfiguration,
|
||||
DatabaseAdapterFlavor,
|
||||
CacheAdapterFlavor,
|
||||
EntityCompanionDefinition,
|
||||
Entity,
|
||||
EntityMutationExecutable,
|
||||
EntityQueryContext,
|
||||
} 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 EntityMutationExecutable<
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 ThrowConditionallyTrigger('name', 'afterCommit')],
|
||||
},
|
||||
});
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
import {
|
||||
AlwaysAllowPrivacyPolicyRule,
|
||||
EntityPrivacyPolicy,
|
||||
ViewerContext,
|
||||
UUIDField,
|
||||
StringField,
|
||||
EntityConfiguration,
|
||||
DatabaseAdapterFlavor,
|
||||
CacheAdapterFlavor,
|
||||
EntityCompanionDefinition,
|
||||
Entity,
|
||||
EntityMutationExecutable,
|
||||
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 EntityMutationExecutable<
|
||||
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')],
|
||||
});
|
||||
+2
-2
@@ -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(),
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
@@ -3,6 +3,14 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [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
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@expo/entity-example",
|
||||
"private": true,
|
||||
"version": "0.5.2",
|
||||
"version": "0.6.0",
|
||||
"description": "An example integration of the @expo/entity framework",
|
||||
"scripts": {
|
||||
"tsc": "tsc",
|
||||
@@ -14,7 +14,7 @@
|
||||
"start": "tsnd --transpile-only --inspect --respawn --no-notify --async-stack-traces --throw-deprecation -- src/index.ts"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
"node": ">=12"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
@@ -22,7 +22,7 @@
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@expo/entity": "^0.5.2",
|
||||
"@expo/entity": "^0.6.0",
|
||||
"apollo-server-koa": "^2.14.2",
|
||||
"graphql": "^15.0.0",
|
||||
"koa": "^2.11.0",
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
import {
|
||||
IEntityQueryContextProvider,
|
||||
EntityQueryContext,
|
||||
EntityNonTransactionalQueryContext,
|
||||
EntityTransactionalQueryContext,
|
||||
} from '@expo/entity';
|
||||
|
||||
export default class InMemoryQueryContextProvider implements IEntityQueryContextProvider {
|
||||
getRegularEntityQueryContext(): EntityQueryContext {
|
||||
return new EntityNonTransactionalQueryContext({});
|
||||
getQueryContext(): EntityNonTransactionalQueryContext {
|
||||
return new EntityNonTransactionalQueryContext({}, this);
|
||||
}
|
||||
|
||||
async runInTransactionAsync<T>(
|
||||
transactionScope: (queryContext: EntityQueryContext) => Promise<T>
|
||||
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>
|
||||
): Promise<T> {
|
||||
return await transactionScope(new EntityTransactionalQueryContext({}));
|
||||
}
|
||||
|
||||
@@ -3,6 +3,25 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [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)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity",
|
||||
"version": "0.5.2",
|
||||
"version": "0.6.0",
|
||||
"description": "A privacy-first data model",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -18,7 +18,7 @@
|
||||
"barrelsby": "barrelsby --directory src --location top --exclude tests__ --singleQuotes --exportDefault --delete"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
"node": ">=12"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
@@ -30,7 +30,6 @@
|
||||
"dataloader": "^2.0.0",
|
||||
"es6-error": "^4.1.1",
|
||||
"invariant": "^2.2.4",
|
||||
"lodash": "^4.17.15",
|
||||
"uuid": "^7.0.3"
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -53,7 +53,7 @@ export default class EntityAssociationLoader<
|
||||
.getViewerContext()
|
||||
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
|
||||
.getQueryContextProvider()
|
||||
.getRegularEntityQueryContext()
|
||||
.getQueryContext()
|
||||
): Promise<Result<TAssociatedEntity>> {
|
||||
const associatedEntityID = this.entity.getField(fieldIdentifyingAssociatedEntity);
|
||||
const loader = this.entity
|
||||
@@ -104,7 +104,7 @@ export default class EntityAssociationLoader<
|
||||
.getViewerContext()
|
||||
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
|
||||
.getQueryContextProvider()
|
||||
.getRegularEntityQueryContext()
|
||||
.getQueryContext()
|
||||
): Promise<readonly Result<TAssociatedEntity>[]> {
|
||||
const thisID = this.entity.getID();
|
||||
const loader = this.entity
|
||||
@@ -158,7 +158,7 @@ export default class EntityAssociationLoader<
|
||||
.getViewerContext()
|
||||
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
|
||||
.getQueryContextProvider()
|
||||
.getRegularEntityQueryContext()
|
||||
.getQueryContext()
|
||||
): Promise<Result<TAssociatedEntity> | null> {
|
||||
const associatedFieldValue = this.entity.getField(fieldIdentifyingAssociatedEntity);
|
||||
const loader = this.entity
|
||||
@@ -212,7 +212,7 @@ export default class EntityAssociationLoader<
|
||||
.getViewerContext()
|
||||
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
|
||||
.getQueryContextProvider()
|
||||
.getRegularEntityQueryContext()
|
||||
.getQueryContext()
|
||||
): Promise<readonly Result<TAssociatedEntity>[]> {
|
||||
const associatedFieldValue = this.entity.getField(fieldIdentifyingAssociatedEntity);
|
||||
const loader = this.entity
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
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';
|
||||
@@ -57,6 +59,20 @@ 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();
|
||||
@@ -67,9 +83,11 @@ export default class EntityCompanion<
|
||||
tableDataCoordinator.dataManager
|
||||
);
|
||||
this.entityMutatorFactory = new EntityMutatorFactory(
|
||||
tableDataCoordinator.entityConfiguration.idField,
|
||||
tableDataCoordinator.entityConfiguration,
|
||||
entityClass,
|
||||
privacyPolicy,
|
||||
mutationValidators,
|
||||
mutationTriggers,
|
||||
this.entityLoaderFactory,
|
||||
tableDataCoordinator.databaseAdapter,
|
||||
metricsAdapter
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
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 IEntityCacheAdapterProvider from './IEntityCacheAdapterProvider';
|
||||
import IEntityDatabaseAdapterProvider from './IEntityDatabaseAdapterProvider';
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -184,6 +218,8 @@ export default class EntityCompanionProvider {
|
||||
entityCompanionDefinition.entityClass,
|
||||
tableDataCoordinator,
|
||||
entityCompanionDefinition.privacyPolicyClass,
|
||||
entityCompanionDefinition.mutationValidators,
|
||||
entityCompanionDefinition.mutationTriggers,
|
||||
this.metricsAdapter
|
||||
);
|
||||
});
|
||||
|
||||
@@ -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 inboundEdges: 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,
|
||||
inboundEdges = [],
|
||||
cacheKeyVersion = 0,
|
||||
databaseAdapterFlavor,
|
||||
cacheAdapterFlavor,
|
||||
@@ -30,6 +33,7 @@ export default class EntityConfiguration<TFields> {
|
||||
idField: keyof TFields;
|
||||
tableName: string;
|
||||
schema: Record<keyof TFields, EntityFieldDefinition>;
|
||||
inboundEdges?: 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.inboundEdges = inboundEdges;
|
||||
|
||||
// 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})`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
associatedEntityClass: 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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
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?: EntityMutationTrigger<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>;
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -1,14 +1,22 @@
|
||||
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,
|
||||
} 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 +35,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 +45,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 +70,24 @@ 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)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -74,7 +114,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;
|
||||
}
|
||||
@@ -88,7 +128,7 @@ export class CreateMutator<
|
||||
return await timeAndLogMutationEventAsync(
|
||||
this.metricsAdapter,
|
||||
EntityMetricsMutationType.CREATE
|
||||
)(this.createInternalAsync());
|
||||
)(this.createInTransactionAsync());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,16 +138,32 @@ export class CreateMutator<
|
||||
return await enforceAsyncResult(this.createAsync());
|
||||
}
|
||||
|
||||
private async createInternalAsync(): Promise<Result<TEntity>> {
|
||||
private async createInTransactionAsync(): Promise<Result<TEntity>> {
|
||||
const internalResult = await this.queryContext.runInTransactionIfNotInTransactionAsync(
|
||||
(innerQueryContext) => this.createInternalAsync(innerQueryContext)
|
||||
);
|
||||
if (internalResult.ok) {
|
||||
await this.executeMutationTriggersOrValidatorsAsync(
|
||||
this.mutationTriggers.afterCommit,
|
||||
this.queryContext,
|
||||
internalResult.value
|
||||
);
|
||||
}
|
||||
return internalResult;
|
||||
}
|
||||
|
||||
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 +171,44 @@ 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);
|
||||
const insertResult = await this.databaseAdapter.insertAsync(queryContext, this.fieldsForEntity);
|
||||
|
||||
const entityLoader = this.entityLoaderFactory.forLoad(this.viewerContext, queryContext);
|
||||
await entityLoader.invalidateFieldsAsync(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
|
||||
);
|
||||
|
||||
return result(newEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,7 +236,7 @@ export class UpdateMutator<
|
||||
constructor(
|
||||
viewerContext: TViewerContext,
|
||||
queryContext: EntityQueryContext,
|
||||
idField: keyof TFields,
|
||||
entityConfiguration: EntityConfiguration<TFields>,
|
||||
entityClass: IEntityClass<
|
||||
TFields,
|
||||
TID,
|
||||
@@ -162,6 +246,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 +275,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 +293,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;
|
||||
@@ -209,7 +309,7 @@ export class UpdateMutator<
|
||||
return await timeAndLogMutationEventAsync(
|
||||
this.metricsAdapter,
|
||||
EntityMetricsMutationType.UPDATE
|
||||
)(this.updateInternalAsync());
|
||||
)(this.updateInTransactionAsync());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -219,12 +319,28 @@ export class UpdateMutator<
|
||||
return await enforceAsyncResult(this.updateAsync());
|
||||
}
|
||||
|
||||
private async updateInternalAsync(): Promise<Result<TEntity>> {
|
||||
private async updateInTransactionAsync(): Promise<Result<TEntity>> {
|
||||
const internalResult = await this.queryContext.runInTransactionIfNotInTransactionAsync(
|
||||
(innerQueryContext) => this.updateInternalAsync(innerQueryContext)
|
||||
);
|
||||
if (internalResult.ok) {
|
||||
await this.executeMutationTriggersOrValidatorsAsync(
|
||||
this.mutationTriggers.afterCommit,
|
||||
this.queryContext,
|
||||
internalResult.value
|
||||
);
|
||||
}
|
||||
return internalResult;
|
||||
}
|
||||
|
||||
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 +348,51 @@ 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);
|
||||
|
||||
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
|
||||
);
|
||||
|
||||
return result(updatedEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -269,7 +416,7 @@ export class DeleteMutator<
|
||||
constructor(
|
||||
viewerContext: TViewerContext,
|
||||
queryContext: EntityQueryContext,
|
||||
idField: keyof TFields,
|
||||
entityConfiguration: EntityConfiguration<TFields>,
|
||||
entityClass: IEntityClass<
|
||||
TFields,
|
||||
TID,
|
||||
@@ -279,6 +426,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 +455,11 @@ export class DeleteMutator<
|
||||
super(
|
||||
viewerContext,
|
||||
queryContext,
|
||||
idField,
|
||||
entityConfiguration,
|
||||
entityClass,
|
||||
privacyPolicy,
|
||||
mutationValidators,
|
||||
mutationTriggers,
|
||||
entityLoaderFactory,
|
||||
databaseAdapter,
|
||||
metricsAdapter
|
||||
@@ -311,7 +474,7 @@ export class DeleteMutator<
|
||||
return await timeAndLogMutationEventAsync(
|
||||
this.metricsAdapter,
|
||||
EntityMetricsMutationType.DELETE
|
||||
)(this.deleteInternalAsync());
|
||||
)(this.deleteInTransactionAsync());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -321,21 +484,208 @@ 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>> {
|
||||
const internalResult = await this.queryContext.runInTransactionIfNotInTransactionAsync(
|
||||
(innerQueryContext) =>
|
||||
this.deleteInternalAsync(
|
||||
innerQueryContext,
|
||||
processedEntityIdentifiersFromTransitiveDeletions,
|
||||
skipDatabaseDeletion
|
||||
)
|
||||
);
|
||||
if (internalResult.ok) {
|
||||
await this.executeMutationTriggersOrValidatorsAsync(
|
||||
this.mutationTriggers.afterCommit,
|
||||
this.queryContext,
|
||||
internalResult.value
|
||||
);
|
||||
}
|
||||
return internalResult.ok ? result() : result(internalResult.reason);
|
||||
}
|
||||
|
||||
private async deleteInternalAsync(
|
||||
queryContext: EntityTransactionalQueryContext,
|
||||
processedEntityIdentifiersFromTransitiveDeletions: Set<string>,
|
||||
skipDatabaseDeletion: boolean
|
||||
): Promise<Result<TEntity>> {
|
||||
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);
|
||||
if (!skipDatabaseDeletion) {
|
||||
await this.databaseAdapter.deleteAsync(
|
||||
queryContext,
|
||||
this.entityConfiguration.idField,
|
||||
this.entity.getID()
|
||||
);
|
||||
}
|
||||
|
||||
const entityLoader = this.entityLoaderFactory.forLoad(this.viewerContext, queryContext);
|
||||
await entityLoader.invalidateFieldsAsync(this.entity.getAllDatabaseFields());
|
||||
|
||||
return result();
|
||||
await this.executeMutationTriggersOrValidatorsAsync(
|
||||
this.mutationTriggers.afterDelete,
|
||||
queryContext,
|
||||
this.entity
|
||||
);
|
||||
await this.executeMutationTriggersOrValidatorsAsync(
|
||||
this.mutationTriggers.afterAll,
|
||||
queryContext,
|
||||
this.entity
|
||||
);
|
||||
|
||||
return result(this.entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.inboundEdges;
|
||||
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.associatedEntityClass.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
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import IEntityQueryContextProvider from './IEntityQueryContextProvider';
|
||||
|
||||
/**
|
||||
* Entity framework representation of transactional and non-transactional database
|
||||
* query execution units.
|
||||
@@ -13,16 +15,43 @@ export abstract class EntityQueryContext {
|
||||
getQueryInterface(): any {
|
||||
return this.queryInterface;
|
||||
}
|
||||
|
||||
abstract async runInTransactionIfNotInTransactionAsync<T>(
|
||||
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>
|
||||
): Promise<T>;
|
||||
}
|
||||
|
||||
export class EntityNonTransactionalQueryContext extends EntityQueryContext {
|
||||
constructor(
|
||||
queryInterface: any,
|
||||
private readonly entityQueryContextProvider: IEntityQueryContextProvider
|
||||
) {
|
||||
super(queryInterface);
|
||||
}
|
||||
|
||||
isInTransaction(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
async runInTransactionIfNotInTransactionAsync<T>(
|
||||
transactionScope: (queryContext: EntityQueryContext) => Promise<T>
|
||||
): Promise<T> {
|
||||
if (this.isInTransaction()) {
|
||||
return await transactionScope(this);
|
||||
} else {
|
||||
return await this.entityQueryContextProvider.runInTransactionAsync(transactionScope);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class EntityTransactionalQueryContext extends EntityQueryContext {
|
||||
isInTransaction(): boolean {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export class EntityNonTransactionalQueryContext extends EntityQueryContext {
|
||||
isInTransaction(): boolean {
|
||||
return false;
|
||||
async runInTransactionIfNotInTransactionAsync<T>(
|
||||
transactionScope: (queryContext: EntityQueryContext) => Promise<T>
|
||||
): Promise<T> {
|
||||
return await transactionScope(this);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import {
|
||||
EntityNonTransactionalQueryContext,
|
||||
EntityTransactionalQueryContext,
|
||||
EntityNonTransactionalQueryContext,
|
||||
} from './EntityQueryContext';
|
||||
|
||||
/**
|
||||
@@ -8,9 +8,9 @@ import {
|
||||
*/
|
||||
export default interface IEntityQueryContextProvider {
|
||||
/**
|
||||
* Vend a regular (non-transactional) entity query context.
|
||||
* Vend an entity query context.
|
||||
*/
|
||||
getRegularEntityQueryContext(): EntityNonTransactionalQueryContext;
|
||||
getQueryContext(): EntityNonTransactionalQueryContext;
|
||||
|
||||
/**
|
||||
* Start a transaction and execute the provided transaction-scoped closure within the transaction.
|
||||
|
||||
@@ -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 { EntityQueryContext } 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();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -168,12 +183,13 @@ export default abstract class ReadonlyEntity<
|
||||
TMSelectedFields
|
||||
>,
|
||||
viewerContext: TMViewerContext2,
|
||||
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<TResult>
|
||||
transactionScope: (queryContext: EntityQueryContext) => Promise<TResult>
|
||||
): Promise<TResult> {
|
||||
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)
|
||||
|
||||
@@ -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',
|
||||
inboundEdges: [ChildEntity],
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: DatabaseAdapterFlavor.POSTGRES,
|
||||
cacheAdapterFlavor: CacheAdapterFlavor.REDIS,
|
||||
});
|
||||
|
||||
const childEntityConfiguration = new EntityConfiguration<ChildFields>({
|
||||
idField: 'id',
|
||||
tableName: 'children',
|
||||
inboundEdges: [GrandChildEntity],
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
parent_id: new UUIDField({
|
||||
columnName: 'parent_id',
|
||||
cache: true,
|
||||
association: {
|
||||
associatedEntityClass: 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: {
|
||||
associatedEntityClass: 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,
|
||||
@@ -96,7 +95,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,
|
||||
@@ -172,7 +171,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,
|
||||
@@ -217,7 +216,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 +238,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);
|
||||
@@ -260,7 +259,7 @@ describe(EntityLoader, () => {
|
||||
|
||||
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 +293,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,16 @@ import {
|
||||
|
||||
import EntityDatabaseAdapter from '../EntityDatabaseAdapter';
|
||||
import EntityLoaderFactory from '../EntityLoaderFactory';
|
||||
import EntityMutationTriggerConfiguration, {
|
||||
EntityMutationTrigger,
|
||||
} from '../EntityMutationTriggerConfiguration';
|
||||
import EntityMutationValidator from '../EntityMutationValidator';
|
||||
import EntityMutatorFactory from '../EntityMutatorFactory';
|
||||
import { EntityQueryContext, EntityNonTransactionalQueryContext } from '../EntityQueryContext';
|
||||
import {
|
||||
EntityTransactionalQueryContext,
|
||||
EntityQueryContext,
|
||||
EntityNonTransactionalQueryContext,
|
||||
} from '../EntityQueryContext';
|
||||
import ViewerContext from '../ViewerContext';
|
||||
import { enforceResultsAsync } from '../entityUtils';
|
||||
import EntityDataManager from '../internal/EntityDataManager';
|
||||
@@ -34,6 +42,155 @@ 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> {}
|
||||
}
|
||||
|
||||
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(EntityNonTransactionalQueryContext),
|
||||
anyOfClass(TestEntity)
|
||||
)
|
||||
).once();
|
||||
};
|
||||
|
||||
const createEntityMutatorFactory = (
|
||||
existingObjects: TestFields[]
|
||||
): {
|
||||
@@ -54,7 +211,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 TestMutationTrigger()],
|
||||
};
|
||||
const privacyPolicy = new TestEntityPrivacyPolicy();
|
||||
const databaseAdapter = new StubDatabaseAdapter<TestFields>(
|
||||
testEntityConfiguration,
|
||||
@@ -80,9 +275,11 @@ const createEntityMutatorFactory = (
|
||||
dataManager
|
||||
);
|
||||
const entityMutatorFactory = new EntityMutatorFactory(
|
||||
testEntityConfiguration.idField,
|
||||
testEntityConfiguration,
|
||||
TestEntity,
|
||||
privacyPolicy,
|
||||
mutationValidators,
|
||||
mutationTriggers,
|
||||
entityLoaderFactory,
|
||||
databaseAdapter,
|
||||
metricsAdapter
|
||||
@@ -92,49 +289,148 @@ 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(),
|
||||
},
|
||||
{
|
||||
customIdField: 'world',
|
||||
stringField: 'huh',
|
||||
testIndexedField: '5',
|
||||
numberField: 1,
|
||||
dateField: new Date(),
|
||||
},
|
||||
]);
|
||||
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(),
|
||||
},
|
||||
{
|
||||
customIdField: 'world',
|
||||
stringField: 'huh',
|
||||
testIndexedField: '5',
|
||||
numberField: 1,
|
||||
dateField: new Date(),
|
||||
},
|
||||
]);
|
||||
|
||||
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(),
|
||||
},
|
||||
{
|
||||
customIdField: 'world',
|
||||
stringField: 'huh',
|
||||
testIndexedField: '5',
|
||||
numberField: 1,
|
||||
dateField: new Date(),
|
||||
},
|
||||
]);
|
||||
|
||||
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(),
|
||||
},
|
||||
{
|
||||
customIdField: 'world',
|
||||
stringField: 'huh',
|
||||
testIndexedField: '5',
|
||||
numberField: 1,
|
||||
dateField: new Date(),
|
||||
},
|
||||
]);
|
||||
|
||||
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',
|
||||
@@ -149,39 +445,160 @@ describe(EntityMutatorFactory, () => {
|
||||
numberField: 3,
|
||||
dateField: new Date(),
|
||||
},
|
||||
]
|
||||
);
|
||||
]);
|
||||
|
||||
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(),
|
||||
},
|
||||
{
|
||||
customIdField: 'world',
|
||||
stringField: 'huh',
|
||||
testIndexedField: '4',
|
||||
numberField: 3,
|
||||
dateField: new Date(),
|
||||
},
|
||||
]);
|
||||
|
||||
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(),
|
||||
},
|
||||
{
|
||||
customIdField: 'world',
|
||||
stringField: 'huh',
|
||||
testIndexedField: '4',
|
||||
numberField: 3,
|
||||
dateField: new Date(),
|
||||
},
|
||||
]);
|
||||
|
||||
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(),
|
||||
},
|
||||
{
|
||||
customIdField: 'world',
|
||||
stringField: 'huh',
|
||||
testIndexedField: '4',
|
||||
numberField: 3,
|
||||
dateField: new Date(),
|
||||
},
|
||||
]);
|
||||
|
||||
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',
|
||||
@@ -189,32 +606,123 @@ describe(EntityMutatorFactory, () => {
|
||||
numberField: 3,
|
||||
dateField: new Date(),
|
||||
},
|
||||
]
|
||||
);
|
||||
]);
|
||||
|
||||
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(),
|
||||
},
|
||||
]);
|
||||
|
||||
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(),
|
||||
},
|
||||
]);
|
||||
|
||||
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(),
|
||||
},
|
||||
]);
|
||||
|
||||
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',
|
||||
@@ -249,7 +757,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 +779,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 +837,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 +856,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 +903,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);
|
||||
|
||||
|
||||
@@ -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',
|
||||
inboundEdges: [CategoryEntity],
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
parent_category_id: new UUIDField({
|
||||
columnName: 'parent_category_id',
|
||||
cache: true,
|
||||
association: {
|
||||
associatedEntityClass: 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,42 @@ 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(),
|
||||
});
|
||||
expect(testEntity.getUniqueIdentifier()).not.toEqual(testEntity2.getUniqueIdentifier());
|
||||
});
|
||||
});
|
||||
|
||||
it('cannot be created without an ID', () => {
|
||||
const viewerContext = instance(mock(ViewerContext));
|
||||
const dataWithoutID = {};
|
||||
@@ -74,7 +111,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);
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
};
|
||||
@@ -16,6 +16,8 @@ export * from './EntityFields';
|
||||
export { default as EntityLoader } from './EntityLoader';
|
||||
export { default as EntityLoaderFactory } from './EntityLoaderFactory';
|
||||
export * from './EntityMutator';
|
||||
export { default as EntityMutationExecutable } from './EntityMutationValidator';
|
||||
export { default as EntityMutationTriggerConfiguration } from './EntityMutationTriggerConfiguration';
|
||||
export { default as EntityMutatorFactory } from './EntityMutatorFactory';
|
||||
export { default as EntityPrivacyPolicy } from './EntityPrivacyPolicy';
|
||||
export * from './EntityPrivacyPolicy';
|
||||
|
||||
@@ -63,7 +63,7 @@ export default class EntityDataManager<TFields> {
|
||||
async (fetcherValues) => {
|
||||
this.metricsAdapter.incrementDataManagerDatabaseLoadCount(fieldValues.length);
|
||||
return await this.databaseAdapter.fetchManyWhereAsync(
|
||||
this.queryContextProvider.getRegularEntityQueryContext(),
|
||||
this.queryContextProvider.getQueryContext(),
|
||||
fieldName,
|
||||
fetcherValues
|
||||
);
|
||||
|
||||
@@ -71,7 +71,7 @@ describe(EntityDataManager, () => {
|
||||
StubQueryContextProvider,
|
||||
new NoOpEntityMetricsAdapter()
|
||||
);
|
||||
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
|
||||
const queryContext = StubQueryContextProvider.getQueryContext();
|
||||
|
||||
const dbSpy = jest.spyOn(databaseAdapter, 'fetchManyWhereAsync');
|
||||
const cacheSpy = jest.spyOn(entityCache, 'readManyThroughAsync');
|
||||
@@ -118,7 +118,7 @@ describe(EntityDataManager, () => {
|
||||
StubQueryContextProvider,
|
||||
new NoOpEntityMetricsAdapter()
|
||||
);
|
||||
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
|
||||
const queryContext = StubQueryContextProvider.getQueryContext();
|
||||
|
||||
const dbSpy = jest.spyOn(databaseAdapter, 'fetchManyWhereAsync');
|
||||
const cacheSpy = jest.spyOn(entityCache, 'readManyThroughAsync');
|
||||
@@ -165,7 +165,7 @@ describe(EntityDataManager, () => {
|
||||
StubQueryContextProvider,
|
||||
new NoOpEntityMetricsAdapter()
|
||||
);
|
||||
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,
|
||||
@@ -207,7 +207,7 @@ describe(EntityDataManager, () => {
|
||||
StubQueryContextProvider,
|
||||
new NoOpEntityMetricsAdapter()
|
||||
);
|
||||
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
|
||||
const queryContext = StubQueryContextProvider.getQueryContext();
|
||||
|
||||
const dbSpy = jest.spyOn(databaseAdapter, 'fetchManyWhereAsync');
|
||||
const cacheSpy = jest.spyOn(entityCache, 'readManyThroughAsync');
|
||||
@@ -242,7 +242,7 @@ describe(EntityDataManager, () => {
|
||||
StubQueryContextProvider,
|
||||
new NoOpEntityMetricsAdapter()
|
||||
);
|
||||
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
|
||||
const queryContext = StubQueryContextProvider.getQueryContext();
|
||||
|
||||
const dbSpy = jest.spyOn(databaseAdapter, 'fetchManyWhereAsync');
|
||||
const cacheSpy = jest.spyOn(entityCache, 'readManyThroughAsync');
|
||||
@@ -285,7 +285,7 @@ describe(EntityDataManager, () => {
|
||||
StubQueryContextProvider,
|
||||
new NoOpEntityMetricsAdapter()
|
||||
);
|
||||
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
|
||||
const queryContext = StubQueryContextProvider.getQueryContext();
|
||||
|
||||
const objectInQuestion = objects.get(testEntityConfiguration.tableName)![1];
|
||||
|
||||
@@ -323,7 +323,7 @@ describe(EntityDataManager, () => {
|
||||
StubQueryContextProvider,
|
||||
new NoOpEntityMetricsAdapter()
|
||||
);
|
||||
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
|
||||
const queryContext = StubQueryContextProvider.getQueryContext();
|
||||
|
||||
const objectInQuestion = objects.get(testEntityConfiguration.tableName)![1];
|
||||
|
||||
@@ -398,7 +398,7 @@ describe(EntityDataManager, () => {
|
||||
StubQueryContextProvider,
|
||||
new NoOpEntityMetricsAdapter()
|
||||
);
|
||||
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
|
||||
const queryContext = StubQueryContextProvider.getQueryContext();
|
||||
|
||||
const dbSpy = jest.spyOn(databaseAdapter, 'fetchManyByFieldEqualityConjunctionAsync');
|
||||
const cacheSpy = jest.spyOn(entityCache, 'readManyThroughAsync');
|
||||
@@ -443,7 +443,7 @@ describe(EntityDataManager, () => {
|
||||
StubQueryContextProvider,
|
||||
new NoOpEntityMetricsAdapter()
|
||||
);
|
||||
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
|
||||
const queryContext = StubQueryContextProvider.getQueryContext();
|
||||
|
||||
await expect(
|
||||
entityDataManager.loadManyByFieldEqualingAsync(queryContext, 'customIdField', ['2'])
|
||||
@@ -469,7 +469,7 @@ describe(EntityDataManager, () => {
|
||||
StubQueryContextProvider,
|
||||
metricsAdapter
|
||||
);
|
||||
const queryContext = StubQueryContextProvider.getRegularEntityQueryContext();
|
||||
const queryContext = StubQueryContextProvider.getQueryContext();
|
||||
|
||||
await entityDataManager.loadManyByFieldEqualingAsync(queryContext, 'customIdField', ['1']);
|
||||
verify(
|
||||
|
||||
@@ -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>>
|
||||
|
||||
@@ -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,17 +1,16 @@
|
||||
import {
|
||||
EntityNonTransactionalQueryContext,
|
||||
EntityQueryContext,
|
||||
EntityTransactionalQueryContext,
|
||||
} from '../../EntityQueryContext';
|
||||
import IEntityQueryContextProvider from '../../IEntityQueryContextProvider';
|
||||
|
||||
class StubQueryContextProvider implements IEntityQueryContextProvider {
|
||||
getRegularEntityQueryContext(): EntityQueryContext {
|
||||
return new EntityNonTransactionalQueryContext({});
|
||||
getQueryContext(): EntityNonTransactionalQueryContext {
|
||||
return new EntityNonTransactionalQueryContext({}, this);
|
||||
}
|
||||
|
||||
async runInTransactionAsync<T>(
|
||||
transactionScope: (queryContext: EntityQueryContext) => Promise<T>
|
||||
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>
|
||||
): Promise<T> {
|
||||
return await transactionScope(new EntityTransactionalQueryContext({}));
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
@@ -58,7 +58,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(
|
||||
@@ -123,7 +123,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(
|
||||
@@ -188,7 +188,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 +201,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 +221,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(
|
||||
@@ -254,7 +254,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(
|
||||
@@ -285,7 +285,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()
|
||||
|
||||
@@ -3,4 +3,11 @@ module.exports = {
|
||||
testMatch: ['**/__integration-tests__/**/*-test.ts'],
|
||||
coveragePathIgnorePatterns: ['testfixtures'],
|
||||
coverageDirectory: 'coverage-integration',
|
||||
globals: {
|
||||
'ts-jest': {
|
||||
diagnostics: {
|
||||
warnOnly: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -2,4 +2,11 @@ module.exports = {
|
||||
preset: 'ts-jest',
|
||||
testMatch: ['**/__tests__/**/*-test.ts'],
|
||||
coveragePathIgnorePatterns: ['testfixtures'],
|
||||
globals: {
|
||||
'ts-jest': {
|
||||
diagnostics: {
|
||||
warnOnly: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2018",
|
||||
"lib": ["es2018"],
|
||||
"target": "es2019",
|
||||
"lib": ["es2019"],
|
||||
"module": "commonjs",
|
||||
"sourceMap": true,
|
||||
"moduleResolution": "node",
|
||||
|
||||
@@ -311,23 +311,22 @@
|
||||
which "^1.3.1"
|
||||
|
||||
"@expo/entity-cache-adapter-redis@file:packages/entity-cache-adapter-redis":
|
||||
version "0.4.0"
|
||||
version "0.5.2"
|
||||
dependencies:
|
||||
ioredis "^4.16.1"
|
||||
|
||||
"@expo/entity-database-adapter-knex@file:packages/entity-database-adapter-knex":
|
||||
version "0.4.0"
|
||||
version "0.5.2"
|
||||
dependencies:
|
||||
knex "^0.20.11"
|
||||
|
||||
"@expo/entity@file:packages/entity":
|
||||
version "0.4.0"
|
||||
version "0.5.2"
|
||||
dependencies:
|
||||
"@expo/results" "^0.3.0"
|
||||
dataloader "^2.0.0"
|
||||
es6-error "^4.1.1"
|
||||
invariant "^2.2.4"
|
||||
lodash "^4.17.15"
|
||||
uuid "^7.0.3"
|
||||
|
||||
"@expo/results@^0.3.0":
|
||||
@@ -1613,11 +1612,6 @@
|
||||
dependencies:
|
||||
"@types/koa" "*"
|
||||
|
||||
"@types/lodash@^4.14.150":
|
||||
version "4.14.150"
|
||||
resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.150.tgz#649fe44684c3f1fcb6164d943c5a61977e8cf0bd"
|
||||
integrity sha512-kMNLM5JBcasgYscD9x/Gvr6lTAv2NVgsKtet/hm93qMyf/D1pt+7jeEZklKJKxMVmXjxbRVQQGfqDSfipYCO6w==
|
||||
|
||||
"@types/long@^4.0.0":
|
||||
version "4.0.1"
|
||||
resolved "https://registry.yarnpkg.com/@types/long/-/long-4.0.1.tgz#459c65fa1867dafe6a8f322c4c51695663cc55e9"
|
||||
|
||||
Reference in new issue
Block a user