mirror of
https://github.com/expo/entity.git
synced 2026-11-21 10:19:25 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b9b09933e5 | ||
|
|
d3e89bdd82 | ||
|
|
b6089524bb | ||
|
|
e054a0d74b | ||
|
|
4ddea7da77 | ||
|
|
8c52ace8d1 | ||
|
|
618383027d | ||
|
|
9758fd5df8 | ||
|
|
8414d96d94 | ||
|
|
ed8528d6a6 | ||
|
|
0ea917ad02 | ||
|
|
485894af16 | ||
|
|
1da5cc01e1 | ||
|
|
b7e524c418 | ||
|
|
d9c1852706 | ||
|
|
ca1b69e2cb | ||
|
|
f0aa0dafeb | ||
|
|
06b3cb7f80 | ||
|
|
ad41af1c82 | ||
|
|
f3a2bf62de | ||
|
|
1d95eba1f9 | ||
|
|
aa56b705db | ||
|
|
ee4be736a9 | ||
|
|
4a2b61f2bd | ||
|
|
a976e76509 | ||
|
|
72f34f0bee |
No files matched your search
@@ -18,7 +18,7 @@
|
||||
],
|
||||
"exclude": [
|
||||
"**/*tests__/**",
|
||||
"**/testfixtures/**"
|
||||
"**/__testfixtures__/**"
|
||||
],
|
||||
"output": "src"
|
||||
}
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
extends: ['universe/node', 'universe/shared/typescript-analysis'],
|
||||
plugins: ['eslint-plugin-tsdoc'],
|
||||
rules: {
|
||||
'no-restricted-imports': ['error', { paths: ['.', '..', '../..'] }],
|
||||
'tsdoc/syntax': 'warn',
|
||||
'no-console': 'warn',
|
||||
'handle-callback-err': 'off',
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
files: ['*.ts', '*.tsx', '*.d.ts'],
|
||||
parserOptions: {
|
||||
project: './tsconfig.json',
|
||||
},
|
||||
rules: {
|
||||
'no-void': ['warn', { allowAsStatement: true }],
|
||||
'@typescript-eslint/explicit-function-return-type': [
|
||||
'warn',
|
||||
{
|
||||
allowExpressions: true,
|
||||
},
|
||||
],
|
||||
'@typescript-eslint/naming-convention': [
|
||||
'warn',
|
||||
{
|
||||
selector: 'typeLike',
|
||||
format: ['PascalCase'],
|
||||
},
|
||||
{
|
||||
selector: 'enumMember',
|
||||
format: ['UPPER_CASE'],
|
||||
},
|
||||
// async functions must have names ending with 'Async'
|
||||
{
|
||||
selector: ['function', 'classMethod', 'typeMethod'],
|
||||
format: ['camelCase'],
|
||||
modifiers: ['async'],
|
||||
suffix: ['Async'],
|
||||
},
|
||||
],
|
||||
'no-dupe-class-members': 'off',
|
||||
'@typescript-eslint/no-dupe-class-members': ['error'],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/__tests__/**/*.ts', '**/__tests__/**/*.tsx', '**/__tests__/**/*.d.ts'],
|
||||
parserOptions: {
|
||||
project: './tsconfig.json',
|
||||
},
|
||||
rules: {
|
||||
// ts-mockito verify function needs void functions within verify which is a void function
|
||||
'@typescript-eslint/no-confusing-void-expression': 'off',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -3,6 +3,75 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.44.0](https://github.com/expo/entity/compare/v0.43.0...v0.44.0) (2025-05-29)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* introduce transactional dataloader mode and fix global transaction ID generation ([#289](https://github.com/expo/entity/issues/289)) ([d3e89bd](https://github.com/expo/entity/commit/d3e89bdd82e6df5c5b35522bc3574fd9e1cfddff))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add transaction-scoped dataloaders ([#284](https://github.com/expo/entity/issues/284)) ([e054a0d](https://github.com/expo/entity/commit/e054a0d74b3a39158ca7d73d05f59d3633113400)), closes [#98](https://github.com/expo/entity/issues/98) [#194](https://github.com/expo/entity/issues/194)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.43.0](https://github.com/expo/entity/compare/v0.42.0...v0.43.0) (2025-04-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* fix generated tsc definition sentinel type visibility ([#283](https://github.com/expo/entity/issues/283)) ([9758fd5](https://github.com/expo/entity/commit/9758fd5df8695a8121258cd988c0c79ce8a3e4b6))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.42.0](https://github.com/expo/entity/compare/v0.41.0...v0.42.0) (2025-04-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* fix metrics for dataloader waterfall logging ([#267](https://github.com/expo/entity/issues/267)) ([1d95eba](https://github.com/expo/entity/commit/1d95eba1f9efb67164c3affc917c9b2514e1529f))
|
||||
* move source of truth of loader docblocks to enforcing loader since it is not the default loader ([#264](https://github.com/expo/entity/issues/264)) ([aa56b70](https://github.com/expo/entity/commit/aa56b705db115cf760125208eb2d3585a3794e58))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add @expo/entity-testing-utils package ([#280](https://github.com/expo/entity/issues/280)) ([485894a](https://github.com/expo/entity/commit/485894af16e233d533a9480285bbda56812cbe0b))
|
||||
* add composite field loading and caching ([#272](https://github.com/expo/entity/issues/272)) ([f0aa0da](https://github.com/expo/entity/commit/f0aa0dafebdb56418cbd22dda437233d850db3e7))
|
||||
* add some utility classes and methods in preparation for composite keys ([#269](https://github.com/expo/entity/issues/269)) ([ad41af1](https://github.com/expo/entity/commit/ad41af1c826fb267f5e463771107c85802578a19)), closes [#201](https://github.com/expo/entity/issues/201)
|
||||
* change entity id field generic to field name and derive type where necessary ([#278](https://github.com/expo/entity/issues/278)) ([b7e524c](https://github.com/expo/entity/commit/b7e524c41892797608d0b884410b8d520a80a9ef))
|
||||
* convert batched/cached loader interface to holder pattern ([#271](https://github.com/expo/entity/issues/271)) ([06b3cb7](https://github.com/expo/entity/commit/06b3cb7f8076ef9e5b83cdf154da159801bd14cc)), closes [#201](https://github.com/expo/entity/issues/201)
|
||||
* enforce explicit id field cache property ([#276](https://github.com/expo/entity/issues/276)) ([1da5cc0](https://github.com/expo/entity/commit/1da5cc01e1affc3b3338a0ab2050504b5853ac6f))
|
||||
* invalidate n+/-1 cacheKeyVersion for entities for push safety ([#275](https://github.com/expo/entity/issues/275)) ([d9c1852](https://github.com/expo/entity/commit/d9c1852706f98f0761ff24ddd244e4ed2beca580))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.41.0](https://github.com/expo/entity/compare/v0.40.0...v0.41.0) (2025-03-07)
|
||||
|
||||
|
||||
* feat!: Default all loaders and mutators to enforcing (#256) ([a976e76](https://github.com/expo/entity/commit/a976e765098bca27049585e43a3bed5c71b9ac6b)), closes [#256](https://github.com/expo/entity/issues/256)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Create codemod for v0.40.0 -> v0.41.0 ([#260](https://github.com/expo/entity/issues/260)) ([4a2b61f](https://github.com/expo/entity/commit/4a2b61f2bd8edfc19109ef4c8ac780eaf0f7795c))
|
||||
|
||||
|
||||
### BREAKING CHANGES
|
||||
|
||||
* Default all loaders and mutators to enforcing
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.40.0](https://github.com/expo/entity/compare/v0.39.0...v0.40.0) (2025-02-27)
|
||||
|
||||
|
||||
|
||||
@@ -82,7 +82,7 @@ Note: The entity framework instance should not be shared across multiple request
|
||||
|
||||
To release a new version:
|
||||
1. `git checkout main`
|
||||
1. `yarn lerna publish [patch|minor|major] -- --conventional-commits`
|
||||
1. `yarn lerna publish [patch|minor|major] -- --conventional-commits --force-publish`
|
||||
1. In GitHub release interface, create a new release from the tag, copy changelog changes to release description.
|
||||
|
||||
## License
|
||||
|
||||
@@ -3,3 +3,4 @@ codecov:
|
||||
ignore:
|
||||
- "packages/entity-example"
|
||||
- "packages/entity-codemod"
|
||||
- "packages/entity-testing-utils"
|
||||
@@ -0,0 +1,82 @@
|
||||
const { defineConfig, globalIgnores } = require('eslint/config');
|
||||
const universeNodeConfig = require('eslint-config-universe/flat/node');
|
||||
const universeSharedTypescriptAnalysisConfig = require('eslint-config-universe/flat/shared/typescript-analysis');
|
||||
const tsdoc = require('eslint-plugin-tsdoc');
|
||||
|
||||
module.exports = defineConfig([
|
||||
globalIgnores(['packages/entity-codemod/**/__testfixtures__/**']),
|
||||
universeNodeConfig,
|
||||
universeSharedTypescriptAnalysisConfig,
|
||||
{
|
||||
plugins: {
|
||||
tsdoc,
|
||||
},
|
||||
rules: {
|
||||
'no-restricted-imports': ['error', { paths: ['.', '..', '../..'] }],
|
||||
'tsdoc/syntax': 'warn',
|
||||
'no-console': 'warn',
|
||||
'handle-callback-err': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
settings: {
|
||||
jest: {
|
||||
version: 29,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.ts', '**/*.tsx', '**/*.d.ts'],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: './tsconfig.json',
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'no-void': [
|
||||
'warn',
|
||||
{
|
||||
allowAsStatement: true,
|
||||
},
|
||||
],
|
||||
'@typescript-eslint/explicit-function-return-type': [
|
||||
'warn',
|
||||
{
|
||||
allowExpressions: true,
|
||||
},
|
||||
],
|
||||
'@typescript-eslint/naming-convention': [
|
||||
'warn',
|
||||
{
|
||||
selector: 'typeLike',
|
||||
format: ['PascalCase'],
|
||||
},
|
||||
{
|
||||
selector: 'enumMember',
|
||||
format: ['UPPER_CASE'],
|
||||
},
|
||||
// async functions must have names ending with 'Async'
|
||||
{
|
||||
selector: ['function', 'classMethod', 'typeMethod'],
|
||||
format: ['camelCase'],
|
||||
modifiers: ['async'],
|
||||
suffix: ['Async'],
|
||||
},
|
||||
],
|
||||
'no-dupe-class-members': 'off',
|
||||
'@typescript-eslint/no-dupe-class-members': ['error'],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/__tests__/**/*.ts', '**/__tests__/**/*.tsx', '**/__tests__/**/*.d.ts'],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: './tsconfig.json',
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
// ts-mockito verify function needs void functions within verify which is a void function
|
||||
'@typescript-eslint/no-confusing-void-expression': 'off',
|
||||
},
|
||||
},
|
||||
]);
|
||||
+1
-1
@@ -3,5 +3,5 @@
|
||||
"packages/*"
|
||||
],
|
||||
"npmClient": "yarn",
|
||||
"version": "0.40.0"
|
||||
"version": "0.44.0"
|
||||
}
|
||||
@@ -3,6 +3,9 @@
|
||||
"tsc": {
|
||||
"dependsOn": ["^clean", "clean", "^tsc"]
|
||||
},
|
||||
"build": {
|
||||
"dependsOn": ["^clean", "clean", "^build"]
|
||||
},
|
||||
"test": {
|
||||
"dependsOn": ["^tsc"]
|
||||
},
|
||||
|
||||
+6
-5
@@ -6,19 +6,20 @@
|
||||
],
|
||||
"scripts": {
|
||||
"tsc": "lerna run tsc",
|
||||
"build": "lerna run build",
|
||||
"clean": "lerna run clean",
|
||||
"lint": "lerna run lint",
|
||||
"lint-fix": "lerna run lint-fix",
|
||||
"test": "lerna run test",
|
||||
"integration": "./resources/run-with-docker lerna run integration-no-setup",
|
||||
"prepack": "lerna run tsc",
|
||||
"prepack": "lerna run build",
|
||||
"ctix": "lerna run ctix",
|
||||
"typedoc": "yarn tsc && typedoc"
|
||||
"typedoc": "yarn build && typedoc"
|
||||
},
|
||||
"devDependencies": {
|
||||
"lerna": "^8.2.0",
|
||||
"typedoc": "^0.27.7",
|
||||
"typescript": "^5.7.3"
|
||||
"lerna": "^8.2.2",
|
||||
"typedoc": "^0.28.4",
|
||||
"typescript": "^5.8.3"
|
||||
},
|
||||
"volta": {
|
||||
"node": "20.14.0"
|
||||
|
||||
@@ -3,6 +3,51 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.44.0](https://github.com/expo/entity/compare/v0.43.0...v0.44.0) (2025-05-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-local-memory
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.43.0](https://github.com/expo/entity/compare/v0.42.0...v0.43.0) (2025-04-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-local-memory
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.42.0](https://github.com/expo/entity/compare/v0.41.0...v0.42.0) (2025-04-10)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add @expo/entity-testing-utils package ([#280](https://github.com/expo/entity/issues/280)) ([485894a](https://github.com/expo/entity/commit/485894af16e233d533a9480285bbda56812cbe0b))
|
||||
* add composite field loading and caching ([#272](https://github.com/expo/entity/issues/272)) ([f0aa0da](https://github.com/expo/entity/commit/f0aa0dafebdb56418cbd22dda437233d850db3e7))
|
||||
* change entity id field generic to field name and derive type where necessary ([#278](https://github.com/expo/entity/issues/278)) ([b7e524c](https://github.com/expo/entity/commit/b7e524c41892797608d0b884410b8d520a80a9ef))
|
||||
* convert batched/cached loader interface to holder pattern ([#271](https://github.com/expo/entity/issues/271)) ([06b3cb7](https://github.com/expo/entity/commit/06b3cb7f8076ef9e5b83cdf154da159801bd14cc)), closes [#201](https://github.com/expo/entity/issues/201)
|
||||
* invalidate n+/-1 cacheKeyVersion for entities for push safety ([#275](https://github.com/expo/entity/issues/275)) ([d9c1852](https://github.com/expo/entity/commit/d9c1852706f98f0761ff24ddd244e4ed2beca580))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.41.0](https://github.com/expo/entity/compare/v0.40.0...v0.41.0) (2025-03-07)
|
||||
|
||||
|
||||
* feat!: Default all loaders and mutators to enforcing (#256) ([a976e76](https://github.com/expo/entity/commit/a976e765098bca27049585e43a3bed5c71b9ac6b)), closes [#256](https://github.com/expo/entity/issues/256)
|
||||
|
||||
|
||||
### BREAKING CHANGES
|
||||
|
||||
* Default all loaders and mutators to enforcing
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.40.0](https://github.com/expo/entity/compare/v0.39.0...v0.40.0) (2025-02-27)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity-cache-adapter-local-memory",
|
||||
"version": "0.40.0",
|
||||
"version": "0.44.0",
|
||||
"description": "Cross-request local memory cache adapter for @expo/entity",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -10,6 +10,7 @@
|
||||
"types": "build/index.d.ts",
|
||||
"scripts": {
|
||||
"tsc": "tsc",
|
||||
"build": "tsc -b tsconfig.build.json",
|
||||
"clean": "rm -rf build coverage coverage-integration",
|
||||
"lint": "eslint src",
|
||||
"lint-fix": "eslint src --fix",
|
||||
@@ -31,18 +32,19 @@
|
||||
"lru-cache": "^6.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.12",
|
||||
"@expo/entity-testing-utils": "workspace:^",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/lru-cache": "^5.1.1",
|
||||
"@types/node": "^20.14.1",
|
||||
"ctix": "^2.7.0",
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-config-universe": "^14.0.0",
|
||||
"eslint-plugin-tsdoc": "^0.3.0",
|
||||
"eslint": "^9.26.0",
|
||||
"eslint-config-universe": "^15.0.3",
|
||||
"eslint-plugin-tsdoc": "^0.4.0",
|
||||
"jest": "^29.7.0",
|
||||
"prettier": "^3.3.3",
|
||||
"prettier": "^3.5.3",
|
||||
"prettier-plugin-organize-imports": "^4.1.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-jest": "^29.3.2",
|
||||
"ts-mockito": "^2.6.1",
|
||||
"typescript": "^5.7.3"
|
||||
"typescript": "^5.8.3"
|
||||
}
|
||||
}
|
||||
@@ -3,27 +3,33 @@ import {
|
||||
CacheStatus,
|
||||
EntityConfiguration,
|
||||
IEntityGenericCacher,
|
||||
IEntityLoadKey,
|
||||
IEntityLoadValue,
|
||||
} from '@expo/entity';
|
||||
import invariant from 'invariant';
|
||||
import LRUCache from 'lru-cache';
|
||||
|
||||
// Sentinel value we store in local memory to negatively cache a database miss.
|
||||
// The sentinel value is distinct from any (positively) cached value.
|
||||
export const DOES_NOT_EXIST_LOCAL_MEMORY_CACHE = Symbol('doesNotExist');
|
||||
export type LocalMemoryCacheValue<TFields> =
|
||||
export type LocalMemoryCacheValue<TFields extends Record<string, any>> =
|
||||
| Readonly<TFields>
|
||||
| typeof DOES_NOT_EXIST_LOCAL_MEMORY_CACHE;
|
||||
export type LocalMemoryCache<TFields> = LRUCache<string, LocalMemoryCacheValue<TFields>>;
|
||||
export type LocalMemoryCache<TFields extends Record<string, any>> = LRUCache<
|
||||
string,
|
||||
LocalMemoryCacheValue<TFields>
|
||||
>;
|
||||
|
||||
export default class GenericLocalMemoryCacher<TFields extends Record<string, any>>
|
||||
implements IEntityGenericCacher<TFields>
|
||||
export default class GenericLocalMemoryCacher<
|
||||
TFields extends Record<string, any>,
|
||||
TIDField extends keyof TFields,
|
||||
> implements IEntityGenericCacher<TFields, TIDField>
|
||||
{
|
||||
constructor(
|
||||
private readonly entityConfiguration: EntityConfiguration<TFields>,
|
||||
private readonly entityConfiguration: EntityConfiguration<TFields, TIDField>,
|
||||
private readonly localMemoryCache: LocalMemoryCache<TFields>,
|
||||
) {}
|
||||
|
||||
static createLRUCache<TFields>(
|
||||
static createLRUCache<TFields extends Record<string, any>>(
|
||||
options: { maxSize?: number; ttlSeconds?: number } = {},
|
||||
): LocalMemoryCache<TFields> {
|
||||
const DEFAULT_LRU_CACHE_MAX_AGE_SECONDS = 10;
|
||||
@@ -36,7 +42,7 @@ export default class GenericLocalMemoryCacher<TFields extends Record<string, any
|
||||
});
|
||||
}
|
||||
|
||||
static createNoOpCache<TFields>(): LocalMemoryCache<TFields> {
|
||||
static createNoOpCache<TFields extends Record<string, any>>(): LocalMemoryCache<TFields> {
|
||||
return new LRUCache<string, LocalMemoryCacheValue<TFields>>({
|
||||
max: 0,
|
||||
maxAge: -1,
|
||||
@@ -85,17 +91,18 @@ export default class GenericLocalMemoryCacher<TFields extends Record<string, any
|
||||
}
|
||||
}
|
||||
|
||||
public makeCacheKey<N extends keyof TFields>(
|
||||
fieldName: N,
|
||||
fieldValue: NonNullable<TFields[N]>,
|
||||
): string {
|
||||
const columnName = this.entityConfiguration.entityToDBFieldsKeyMapping.get(fieldName);
|
||||
invariant(columnName, `database field mapping missing for ${String(fieldName)}`);
|
||||
public makeCacheKeyForStorage<
|
||||
TLoadKey extends IEntityLoadKey<TFields, TIDField, TSerializedLoadValue, TLoadValue>,
|
||||
TSerializedLoadValue,
|
||||
TLoadValue extends IEntityLoadValue<TSerializedLoadValue>,
|
||||
>(key: TLoadKey, value: TLoadValue): string {
|
||||
const cacheKeyType = key.getLoadMethodType();
|
||||
const keyAndValueParts = key.createCacheKeyPartsForLoadValue(this.entityConfiguration, value);
|
||||
const parts = [
|
||||
this.entityConfiguration.tableName,
|
||||
cacheKeyType,
|
||||
`${this.entityConfiguration.cacheKeyVersion}`,
|
||||
columnName,
|
||||
String(fieldValue),
|
||||
...keyAndValueParts,
|
||||
];
|
||||
|
||||
const delimiter = ':';
|
||||
@@ -104,4 +111,14 @@ export default class GenericLocalMemoryCacher<TFields extends Record<string, any
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
}
|
||||
|
||||
public makeCacheKeysForInvalidation<
|
||||
TLoadKey extends IEntityLoadKey<TFields, TIDField, TSerializedLoadValue, TLoadValue>,
|
||||
TSerializedLoadValue,
|
||||
TLoadValue extends IEntityLoadValue<TSerializedLoadValue>,
|
||||
>(key: TLoadKey, value: TLoadValue): readonly string[] {
|
||||
// for local memory caches, we don't need to invalidate old versions of the cache keys
|
||||
// since they are not persisted across deploys
|
||||
return [this.makeCacheKeyForStorage(key, value)];
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ export default class LocalMemoryCacheAdapterProvider implements IEntityCacheAdap
|
||||
* @returns a no-op local memory cache adapter provider, or one that doesn't cache locally.
|
||||
*/
|
||||
static createNoOpProvider(): IEntityCacheAdapterProvider {
|
||||
return new LocalMemoryCacheAdapterProvider(<TFields>() =>
|
||||
return new LocalMemoryCacheAdapterProvider(<TFields extends Record<string, any>>() =>
|
||||
GenericLocalMemoryCacher.createNoOpCache<TFields>(),
|
||||
);
|
||||
}
|
||||
@@ -28,20 +28,25 @@ export default class LocalMemoryCacheAdapterProvider implements IEntityCacheAdap
|
||||
static createProviderWithOptions(
|
||||
options: { maxSize?: number; ttlSeconds?: number } = {},
|
||||
): IEntityCacheAdapterProvider {
|
||||
return new LocalMemoryCacheAdapterProvider(<TFields>() =>
|
||||
return new LocalMemoryCacheAdapterProvider(<TFields extends Record<string, any>>() =>
|
||||
GenericLocalMemoryCacher.createLRUCache<TFields>(options),
|
||||
);
|
||||
}
|
||||
|
||||
private readonly localMemoryCacheAdapterMap = new Map<string, GenericEntityCacheAdapter<any>>();
|
||||
private readonly localMemoryCacheAdapterMap = new Map<
|
||||
string,
|
||||
GenericEntityCacheAdapter<any, any>
|
||||
>();
|
||||
|
||||
private constructor(
|
||||
private readonly localMemoryCacheCreator: <TFields>() => LocalMemoryCache<TFields>,
|
||||
private readonly localMemoryCacheCreator: <
|
||||
TFields extends Record<string, any>,
|
||||
>() => LocalMemoryCache<TFields>,
|
||||
) {}
|
||||
|
||||
public getCacheAdapter<TFields extends Record<string, any>>(
|
||||
entityConfiguration: EntityConfiguration<TFields>,
|
||||
): IEntityCacheAdapter<TFields> {
|
||||
public getCacheAdapter<TFields extends Record<string, any>, TIDField extends keyof TFields>(
|
||||
entityConfiguration: EntityConfiguration<TFields, TIDField>,
|
||||
): IEntityCacheAdapter<TFields, TIDField> {
|
||||
return computeIfAbsent(this.localMemoryCacheAdapterMap, entityConfiguration.tableName, () => {
|
||||
const localMemoryCache = this.localMemoryCacheCreator<TFields>();
|
||||
return new GenericEntityCacheAdapter(
|
||||
|
||||
+30
-28
@@ -2,12 +2,12 @@ import {
|
||||
AlwaysAllowPrivacyPolicyRule,
|
||||
EntityPrivacyPolicy,
|
||||
ViewerContext,
|
||||
UUIDField,
|
||||
DateField,
|
||||
StringField,
|
||||
EntityConfiguration,
|
||||
EntityCompanionDefinition,
|
||||
Entity,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
|
||||
export type LocalMemoryTestEntityFields = {
|
||||
@@ -18,12 +18,12 @@ export type LocalMemoryTestEntityFields = {
|
||||
|
||||
export default class LocalMemoryTestEntity extends Entity<
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext
|
||||
> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
LocalMemoryTestEntity,
|
||||
LocalMemoryTestEntityPrivacyPolicy
|
||||
@@ -38,14 +38,14 @@ export default class LocalMemoryTestEntity extends Entity<
|
||||
|
||||
export class LocalMemoryTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
LocalMemoryTestEntity
|
||||
> {
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
LocalMemoryTestEntity
|
||||
>(),
|
||||
@@ -53,7 +53,7 @@ export class LocalMemoryTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
LocalMemoryTestEntity
|
||||
>(),
|
||||
@@ -61,7 +61,7 @@ export class LocalMemoryTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
LocalMemoryTestEntity
|
||||
>(),
|
||||
@@ -69,30 +69,32 @@ export class LocalMemoryTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
LocalMemoryTestEntity
|
||||
>(),
|
||||
];
|
||||
}
|
||||
|
||||
export const localMemoryTestEntityConfiguration =
|
||||
new EntityConfiguration<LocalMemoryTestEntityFields>({
|
||||
idField: 'id',
|
||||
tableName: 'local_memory_test_entities',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
name: new StringField({
|
||||
columnName: 'name',
|
||||
cache: true,
|
||||
}),
|
||||
dateField: new DateField({
|
||||
columnName: 'date_field',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'local-memory',
|
||||
});
|
||||
export const localMemoryTestEntityConfiguration = new EntityConfiguration<
|
||||
LocalMemoryTestEntityFields,
|
||||
'id'
|
||||
>({
|
||||
idField: 'id',
|
||||
tableName: 'local_memory_test_entities',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
name: new StringField({
|
||||
columnName: 'name',
|
||||
cache: true,
|
||||
}),
|
||||
dateField: new DateField({
|
||||
columnName: 'date_field',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'local-memory',
|
||||
});
|
||||
+1
-2
@@ -2,9 +2,8 @@ import {
|
||||
NoOpEntityMetricsAdapter,
|
||||
IEntityMetricsAdapter,
|
||||
EntityCompanionProvider,
|
||||
StubQueryContextProvider,
|
||||
StubDatabaseAdapterProvider,
|
||||
} from '@expo/entity';
|
||||
import { StubDatabaseAdapterProvider, StubQueryContextProvider } from '@expo/entity-testing-utils';
|
||||
|
||||
import LocalMemoryCacheAdapterProvider from '../LocalMemoryCacheAdapterProvider';
|
||||
|
||||
+83
-47
@@ -2,39 +2,44 @@ import {
|
||||
CacheAdapterFlavor,
|
||||
CacheAdapterFlavorDefinition,
|
||||
CacheStatus,
|
||||
IEntityGenericCacher,
|
||||
SingleFieldHolder,
|
||||
SingleFieldValueHolder,
|
||||
ViewerContext,
|
||||
} from '@expo/entity';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import GenericLocalMemoryCacher from '../GenericLocalMemoryCacher';
|
||||
import LocalMemoryCacheAdapterProvider from '../LocalMemoryCacheAdapterProvider';
|
||||
import LocalMemoryTestEntity from '../testfixtures/LocalMemoryTestEntity';
|
||||
import LocalMemoryTestEntity, {
|
||||
LocalMemoryTestEntityFields,
|
||||
} from '../__testfixtures__/LocalMemoryTestEntity';
|
||||
import {
|
||||
createLocalMemoryTestEntityCompanionProvider,
|
||||
createNoOpLocalMemoryIntegrationTestEntityCompanionProvider,
|
||||
} from '../testfixtures/createLocalMemoryTestEntityCompanionProvider';
|
||||
} from '../__testfixtures__/createLocalMemoryTestEntityCompanionProvider';
|
||||
|
||||
describe(GenericLocalMemoryCacher, () => {
|
||||
it('has correct caching behavior', async () => {
|
||||
const entityCompanionProvider = createLocalMemoryTestEntityCompanionProvider();
|
||||
const viewerContext = new ViewerContext(entityCompanionProvider);
|
||||
const genericCacher =
|
||||
viewerContext.entityCompanionProvider.getCompanionForEntity(LocalMemoryTestEntity)[
|
||||
'tableDataCoordinator'
|
||||
]['cacheAdapter']['genericCacher'];
|
||||
const cacheKeyMaker = genericCacher['makeCacheKey'].bind(genericCacher);
|
||||
const genericCacher = viewerContext.entityCompanionProvider.getCompanionForEntity(
|
||||
LocalMemoryTestEntity,
|
||||
)['tableDataCoordinator']['cacheAdapter']['genericCacher'] as IEntityGenericCacher<
|
||||
LocalMemoryTestEntityFields,
|
||||
'id'
|
||||
>;
|
||||
|
||||
const date = new Date();
|
||||
const entity1Created = await LocalMemoryTestEntity.creator(viewerContext)
|
||||
.enforcing()
|
||||
.setField('name', 'blah')
|
||||
.setField('dateField', date)
|
||||
.createAsync();
|
||||
|
||||
// loading an entity should put it in cache
|
||||
const entity1 = await LocalMemoryTestEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadByIDAsync(entity1Created.getID());
|
||||
const entity1 = await LocalMemoryTestEntity.loader(viewerContext).loadByIDAsync(
|
||||
entity1Created.getID(),
|
||||
);
|
||||
|
||||
const localMemoryCacheAdapterProvider = (
|
||||
entityCompanionProvider['cacheAdapterFlavors'] as ReadonlyMap<
|
||||
@@ -47,11 +52,19 @@ describe(GenericLocalMemoryCacher, () => {
|
||||
].get(
|
||||
viewerContext.entityCompanionProvider.getCompanionForEntity(LocalMemoryTestEntity)
|
||||
.entityCompanionDefinition.entityConfiguration.tableName,
|
||||
)!['genericCacher'];
|
||||
)!['genericCacher'] as IEntityGenericCacher<LocalMemoryTestEntityFields, 'id'>;
|
||||
const cachedResult = await entitySpecificGenericCacher.loadManyAsync([
|
||||
cacheKeyMaker('id', entity1.getID()),
|
||||
genericCacher.makeCacheKeyForStorage(
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder(entity1.getID()),
|
||||
),
|
||||
]);
|
||||
const cachedValue = cachedResult.get(cacheKeyMaker('id', entity1.getID()))!;
|
||||
const cachedValue = cachedResult.get(
|
||||
genericCacher.makeCacheKeyForStorage(
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder(entity1.getID()),
|
||||
),
|
||||
)!;
|
||||
expect(cachedValue).toMatchObject({
|
||||
status: CacheStatus.HIT,
|
||||
item: {
|
||||
@@ -64,55 +77,71 @@ describe(GenericLocalMemoryCacher, () => {
|
||||
// simulate non existent db fetch, should write negative result ('') to cache
|
||||
const nonExistentId = uuidv4();
|
||||
|
||||
const entityNonExistentResult = await LocalMemoryTestEntity.loader(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
.loadByIDAsync(nonExistentId);
|
||||
const entityNonExistentResult =
|
||||
await LocalMemoryTestEntity.loaderWithAuthorizationResults(viewerContext).loadByIDAsync(
|
||||
nonExistentId,
|
||||
);
|
||||
expect(entityNonExistentResult.ok).toBe(false);
|
||||
|
||||
const nonExistentCachedResult = await entitySpecificGenericCacher.loadManyAsync([
|
||||
cacheKeyMaker('id', nonExistentId),
|
||||
genericCacher.makeCacheKeyForStorage(
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder(nonExistentId),
|
||||
),
|
||||
]);
|
||||
expect(nonExistentCachedResult.get(cacheKeyMaker('id', nonExistentId))).toMatchObject({
|
||||
expect(
|
||||
nonExistentCachedResult.get(
|
||||
genericCacher.makeCacheKeyForStorage(
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder(nonExistentId),
|
||||
),
|
||||
),
|
||||
).toMatchObject({
|
||||
status: CacheStatus.NEGATIVE,
|
||||
});
|
||||
|
||||
// load again through entities framework to ensure it reads negative result
|
||||
const entityNonExistentResult2 = await LocalMemoryTestEntity.loader(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
.loadByIDAsync(nonExistentId);
|
||||
const entityNonExistentResult2 =
|
||||
await LocalMemoryTestEntity.loaderWithAuthorizationResults(viewerContext).loadByIDAsync(
|
||||
nonExistentId,
|
||||
);
|
||||
expect(entityNonExistentResult2.ok).toBe(false);
|
||||
|
||||
// invalidate from cache to ensure it invalidates correctly
|
||||
await LocalMemoryTestEntity.loader(viewerContext)
|
||||
.utils()
|
||||
.invalidateFieldsAsync(entity1.getAllFields());
|
||||
const cachedResultMiss = await entitySpecificGenericCacher.loadManyAsync([
|
||||
cacheKeyMaker('id', entity1.getID()),
|
||||
]);
|
||||
const cachedValueMiss = cachedResultMiss.get(cacheKeyMaker('id', entity1.getID()));
|
||||
expect(cachedValueMiss).toMatchObject({ status: CacheStatus.MISS });
|
||||
await LocalMemoryTestEntity.loaderUtils(viewerContext).invalidateFieldsAsync(
|
||||
entity1.getAllFields(),
|
||||
);
|
||||
const keys = genericCacher.makeCacheKeysForInvalidation(
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder(entity1.getID()),
|
||||
);
|
||||
const cachedResultMiss = await entitySpecificGenericCacher.loadManyAsync(keys);
|
||||
expect(Array.from(cachedResultMiss.values()).every((v) => v.status === CacheStatus.MISS)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('respects the parameters of a noop cache', async () => {
|
||||
const entityCompanionProvider = createNoOpLocalMemoryIntegrationTestEntityCompanionProvider();
|
||||
const viewerContext = new ViewerContext(entityCompanionProvider);
|
||||
const genericCacher =
|
||||
viewerContext.entityCompanionProvider.getCompanionForEntity(LocalMemoryTestEntity)[
|
||||
'tableDataCoordinator'
|
||||
]['cacheAdapter']['genericCacher'];
|
||||
const cacheKeyMaker = genericCacher['makeCacheKey'].bind(genericCacher);
|
||||
const genericCacher = viewerContext.entityCompanionProvider.getCompanionForEntity(
|
||||
LocalMemoryTestEntity,
|
||||
)['tableDataCoordinator']['cacheAdapter']['genericCacher'] as IEntityGenericCacher<
|
||||
LocalMemoryTestEntityFields,
|
||||
'id'
|
||||
>;
|
||||
const cacheKeyMaker = genericCacher['makeCacheKeyForStorage'].bind(genericCacher);
|
||||
|
||||
const date = new Date();
|
||||
const entity1Created = await LocalMemoryTestEntity.creator(viewerContext)
|
||||
.enforcing()
|
||||
.setField('name', 'blah')
|
||||
.setField('dateField', date)
|
||||
.createAsync();
|
||||
|
||||
// loading an entity will try to put it in cache but it's a noop cache, so it should be a miss
|
||||
const entity1 = await LocalMemoryTestEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadByIDAsync(entity1Created.getID());
|
||||
const entity1 = await LocalMemoryTestEntity.loader(viewerContext).loadByIDAsync(
|
||||
entity1Created.getID(),
|
||||
);
|
||||
|
||||
const localMemoryCacheAdapterProvider = (
|
||||
entityCompanionProvider['cacheAdapterFlavors'] as ReadonlyMap<
|
||||
@@ -125,11 +154,13 @@ describe(GenericLocalMemoryCacher, () => {
|
||||
].get(
|
||||
viewerContext.entityCompanionProvider.getCompanionForEntity(LocalMemoryTestEntity)
|
||||
.entityCompanionDefinition.entityConfiguration.tableName,
|
||||
)!['genericCacher'];
|
||||
)!['genericCacher'] as IEntityGenericCacher<LocalMemoryTestEntityFields, 'id'>;
|
||||
const cachedResult = await entitySpecificGenericCacher.loadManyAsync([
|
||||
cacheKeyMaker('id', entity1.getID()),
|
||||
cacheKeyMaker(new SingleFieldHolder('id'), new SingleFieldValueHolder(entity1.getID())),
|
||||
]);
|
||||
const cachedValue = cachedResult.get(cacheKeyMaker('id', entity1.getID()))!;
|
||||
const cachedValue = cachedResult.get(
|
||||
cacheKeyMaker(new SingleFieldHolder('id'), new SingleFieldValueHolder(entity1.getID())),
|
||||
)!;
|
||||
expect(cachedValue).toMatchObject({
|
||||
status: CacheStatus.MISS,
|
||||
});
|
||||
@@ -137,15 +168,20 @@ describe(GenericLocalMemoryCacher, () => {
|
||||
// a non existent db fetch should try to write negative result ('') but it's a noop cache, so it should be a miss
|
||||
const nonExistentId = uuidv4();
|
||||
|
||||
const entityNonExistentResult = await LocalMemoryTestEntity.loader(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
.loadByIDAsync(nonExistentId);
|
||||
const entityNonExistentResult =
|
||||
await LocalMemoryTestEntity.loaderWithAuthorizationResults(viewerContext).loadByIDAsync(
|
||||
nonExistentId,
|
||||
);
|
||||
expect(entityNonExistentResult.ok).toBe(false);
|
||||
|
||||
const nonExistentCachedResult = await entitySpecificGenericCacher.loadManyAsync([
|
||||
cacheKeyMaker('id', nonExistentId),
|
||||
cacheKeyMaker(new SingleFieldHolder('id'), new SingleFieldValueHolder(nonExistentId)),
|
||||
]);
|
||||
expect(nonExistentCachedResult.get(cacheKeyMaker('id', nonExistentId))).toMatchObject({
|
||||
expect(
|
||||
nonExistentCachedResult.get(
|
||||
cacheKeyMaker(new SingleFieldHolder('id'), new SingleFieldValueHolder(nonExistentId)),
|
||||
),
|
||||
).toMatchObject({
|
||||
status: CacheStatus.MISS,
|
||||
});
|
||||
});
|
||||
|
||||
+74
-28
@@ -1,8 +1,11 @@
|
||||
import {
|
||||
CacheStatus,
|
||||
UUIDField,
|
||||
EntityConfiguration,
|
||||
GenericEntityCacheAdapter,
|
||||
SingleFieldHolder,
|
||||
SingleFieldValueHolder,
|
||||
SingleFieldValueHolderMap,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
|
||||
import GenericLocalMemoryCacher, {
|
||||
@@ -13,7 +16,7 @@ type BlahFields = {
|
||||
id: string;
|
||||
};
|
||||
|
||||
const entityConfiguration = new EntityConfiguration<BlahFields>({
|
||||
const entityConfiguration = new EntityConfiguration<BlahFields, 'id'>({
|
||||
idField: 'id',
|
||||
tableName: 'blah',
|
||||
schema: {
|
||||
@@ -60,34 +63,48 @@ describe('Use within GenericEntityCacheAdapter', () => {
|
||||
),
|
||||
);
|
||||
|
||||
const cacheHits = new Map<string, Readonly<BlahFields>>([['test-id-1', { id: 'test-id-1' }]]);
|
||||
await cacheAdapter.cacheManyAsync('id', cacheHits);
|
||||
await cacheAdapter.cacheDBMissesAsync('id', ['test-id-2']);
|
||||
|
||||
const results = await cacheAdapter.loadManyAsync('id', [
|
||||
'test-id-1',
|
||||
'test-id-2',
|
||||
'test-id-3',
|
||||
const cacheHits = new Map<SingleFieldValueHolder<BlahFields, 'id'>, Readonly<BlahFields>>([
|
||||
[new SingleFieldValueHolder('test-id-1'), { id: 'test-id-1' }],
|
||||
]);
|
||||
await cacheAdapter.cacheManyAsync(
|
||||
new SingleFieldHolder<BlahFields, 'id', 'id'>('id'),
|
||||
cacheHits,
|
||||
);
|
||||
await cacheAdapter.cacheDBMissesAsync(new SingleFieldHolder('id'), [
|
||||
new SingleFieldValueHolder('test-id-2'),
|
||||
]);
|
||||
|
||||
expect(results.get('test-id-1')).toMatchObject({
|
||||
const results = await cacheAdapter.loadManyAsync(new SingleFieldHolder('id'), [
|
||||
new SingleFieldValueHolder('test-id-1'),
|
||||
new SingleFieldValueHolder('test-id-2'),
|
||||
new SingleFieldValueHolder('test-id-3'),
|
||||
]);
|
||||
|
||||
expect(results.get(new SingleFieldValueHolder('test-id-1'))).toMatchObject({
|
||||
status: CacheStatus.HIT,
|
||||
item: { id: 'test-id-1' },
|
||||
});
|
||||
expect(results.get('test-id-2')).toMatchObject({ status: CacheStatus.NEGATIVE });
|
||||
expect(results.get('test-id-3')).toMatchObject({ status: CacheStatus.MISS });
|
||||
expect(results.get(new SingleFieldValueHolder('test-id-2'))).toMatchObject({
|
||||
status: CacheStatus.NEGATIVE,
|
||||
});
|
||||
expect(results.get(new SingleFieldValueHolder('test-id-3'))).toMatchObject({
|
||||
status: CacheStatus.MISS,
|
||||
});
|
||||
expect(results.size).toBe(3);
|
||||
});
|
||||
|
||||
it('returns empty map when passed empty array of fieldValues', async () => {
|
||||
it('returns empty map when passed empty array of values', async () => {
|
||||
const cacheAdapter = new GenericEntityCacheAdapter(
|
||||
new GenericLocalMemoryCacher(
|
||||
entityConfiguration,
|
||||
GenericLocalMemoryCacher.createLRUCache(),
|
||||
),
|
||||
);
|
||||
const results = await cacheAdapter.loadManyAsync('id', []);
|
||||
expect(results).toEqual(new Map());
|
||||
const results = await cacheAdapter.loadManyAsync(
|
||||
new SingleFieldHolder<BlahFields, 'id', 'id'>('id'),
|
||||
[] as SingleFieldValueHolder<BlahFields, 'id'>[],
|
||||
);
|
||||
expect(results).toEqual(new SingleFieldValueHolderMap(new Map()));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -97,9 +114,15 @@ describe('Use within GenericEntityCacheAdapter', () => {
|
||||
|
||||
const localMemoryCacher = new GenericLocalMemoryCacher(entityConfiguration, localMemoryCache);
|
||||
const cacheAdapter = new GenericEntityCacheAdapter(localMemoryCacher);
|
||||
await cacheAdapter.cacheManyAsync('id', new Map([['test-id-1', { id: 'test-id-1' }]]));
|
||||
await cacheAdapter.cacheManyAsync(
|
||||
new SingleFieldHolder('id'),
|
||||
new Map([[new SingleFieldValueHolder('test-id-1'), { id: 'test-id-1' }]]),
|
||||
);
|
||||
|
||||
const cacheKey = localMemoryCacher['makeCacheKey']('id', 'test-id-1');
|
||||
const cacheKey = localMemoryCacher['makeCacheKeyForStorage'](
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder('test-id-1'),
|
||||
);
|
||||
expect(localMemoryCache.get(cacheKey)).toMatchObject({
|
||||
id: 'test-id-1',
|
||||
});
|
||||
@@ -112,9 +135,14 @@ describe('Use within GenericEntityCacheAdapter', () => {
|
||||
|
||||
const localMemoryCacher = new GenericLocalMemoryCacher(entityConfiguration, localMemoryCache);
|
||||
const cacheAdapter = new GenericEntityCacheAdapter(localMemoryCacher);
|
||||
await cacheAdapter.cacheDBMissesAsync('id', ['test-id-1']);
|
||||
await cacheAdapter.cacheDBMissesAsync(new SingleFieldHolder('id'), [
|
||||
new SingleFieldValueHolder('test-id-1'),
|
||||
]);
|
||||
|
||||
const cacheKey = localMemoryCacher['makeCacheKey']('id', 'test-id-1');
|
||||
const cacheKey = localMemoryCacher['makeCacheKeyForStorage'](
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder('test-id-1'),
|
||||
);
|
||||
expect(localMemoryCache.get(cacheKey)).toEqual(DOES_NOT_EXIST_LOCAL_MEMORY_CACHE);
|
||||
});
|
||||
});
|
||||
@@ -126,23 +154,41 @@ describe('Use within GenericEntityCacheAdapter', () => {
|
||||
const cacheAdapter = new GenericEntityCacheAdapter(
|
||||
new GenericLocalMemoryCacher(entityConfiguration, localMemoryCache),
|
||||
);
|
||||
await cacheAdapter.cacheManyAsync('id', new Map([['test-id-1', { id: 'test-id-1' }]]));
|
||||
await cacheAdapter.cacheDBMissesAsync('id', ['test-id-2']);
|
||||
await cacheAdapter.invalidateManyAsync('id', ['test-id-1', 'test-id-2']);
|
||||
await cacheAdapter.cacheManyAsync(
|
||||
new SingleFieldHolder('id'),
|
||||
new Map([[new SingleFieldValueHolder('test-id-1'), { id: 'test-id-1' }]]),
|
||||
);
|
||||
await cacheAdapter.cacheDBMissesAsync(new SingleFieldHolder('id'), [
|
||||
new SingleFieldValueHolder('test-id-2'),
|
||||
]);
|
||||
await cacheAdapter.invalidateManyAsync(new SingleFieldHolder('id'), [
|
||||
new SingleFieldValueHolder('test-id-1'),
|
||||
new SingleFieldValueHolder('test-id-2'),
|
||||
]);
|
||||
|
||||
const results = await cacheAdapter.loadManyAsync('id', ['test-id-1', 'test-id-2']);
|
||||
expect(results.get('test-id-1')).toMatchObject({ status: CacheStatus.MISS });
|
||||
expect(results.get('test-id-2')).toMatchObject({ status: CacheStatus.MISS });
|
||||
const results = await cacheAdapter.loadManyAsync(new SingleFieldHolder('id'), [
|
||||
new SingleFieldValueHolder('test-id-1'),
|
||||
new SingleFieldValueHolder('test-id-2'),
|
||||
]);
|
||||
expect(results.get(new SingleFieldValueHolder('test-id-1'))).toMatchObject({
|
||||
status: CacheStatus.MISS,
|
||||
});
|
||||
expect(results.get(new SingleFieldValueHolder('test-id-2'))).toMatchObject({
|
||||
status: CacheStatus.MISS,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns when passed empty array of fieldValues', async () => {
|
||||
it('returns when passed empty array of values', async () => {
|
||||
const cacheAdapter = new GenericEntityCacheAdapter(
|
||||
new GenericLocalMemoryCacher(
|
||||
entityConfiguration,
|
||||
GenericLocalMemoryCacher.createLRUCache<BlahFields>({}),
|
||||
),
|
||||
);
|
||||
await cacheAdapter.invalidateManyAsync('id', []);
|
||||
await cacheAdapter.invalidateManyAsync(
|
||||
new SingleFieldHolder<BlahFields, 'id', 'id'>('id'),
|
||||
[] as SingleFieldValueHolder<BlahFields, 'id'>[],
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.build.json",
|
||||
"include": ["src"],
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "build",
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -3,6 +3,51 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.44.0](https://github.com/expo/entity/compare/v0.43.0...v0.44.0) (2025-05-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.43.0](https://github.com/expo/entity/compare/v0.42.0...v0.43.0) (2025-04-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.42.0](https://github.com/expo/entity/compare/v0.41.0...v0.42.0) (2025-04-10)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add @expo/entity-testing-utils package ([#280](https://github.com/expo/entity/issues/280)) ([485894a](https://github.com/expo/entity/commit/485894af16e233d533a9480285bbda56812cbe0b))
|
||||
* add composite field loading and caching ([#272](https://github.com/expo/entity/issues/272)) ([f0aa0da](https://github.com/expo/entity/commit/f0aa0dafebdb56418cbd22dda437233d850db3e7))
|
||||
* change entity id field generic to field name and derive type where necessary ([#278](https://github.com/expo/entity/issues/278)) ([b7e524c](https://github.com/expo/entity/commit/b7e524c41892797608d0b884410b8d520a80a9ef))
|
||||
* convert batched/cached loader interface to holder pattern ([#271](https://github.com/expo/entity/issues/271)) ([06b3cb7](https://github.com/expo/entity/commit/06b3cb7f8076ef9e5b83cdf154da159801bd14cc)), closes [#201](https://github.com/expo/entity/issues/201)
|
||||
* invalidate n+/-1 cacheKeyVersion for entities for push safety ([#275](https://github.com/expo/entity/issues/275)) ([d9c1852](https://github.com/expo/entity/commit/d9c1852706f98f0761ff24ddd244e4ed2beca580))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.41.0](https://github.com/expo/entity/compare/v0.40.0...v0.41.0) (2025-03-07)
|
||||
|
||||
|
||||
* feat!: Default all loaders and mutators to enforcing (#256) ([a976e76](https://github.com/expo/entity/commit/a976e765098bca27049585e43a3bed5c71b9ac6b)), closes [#256](https://github.com/expo/entity/issues/256)
|
||||
|
||||
|
||||
### BREAKING CHANGES
|
||||
|
||||
* Default all loaders and mutators to enforcing
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.40.0](https://github.com/expo/entity/compare/v0.39.0...v0.40.0) (2025-02-27)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity-cache-adapter-redis",
|
||||
"version": "0.40.0",
|
||||
"version": "0.44.0",
|
||||
"description": "Redis cache adapter for @expo/entity",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -10,6 +10,7 @@
|
||||
"types": "build/index.d.ts",
|
||||
"scripts": {
|
||||
"tsc": "tsc",
|
||||
"build": "tsc -b tsconfig.build.json",
|
||||
"clean": "rm -rf build coverage coverage-integration",
|
||||
"lint": "eslint src",
|
||||
"lint-fix": "eslint src --fix",
|
||||
@@ -34,18 +35,19 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/batcher": "^1.0.0",
|
||||
"@types/jest": "^29.5.12",
|
||||
"@expo/entity-testing-utils": "workspace:^",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^20.14.1",
|
||||
"ctix": "^2.7.0",
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-config-universe": "^14.0.0",
|
||||
"eslint-plugin-tsdoc": "^0.3.0",
|
||||
"ioredis": "^5.4.1",
|
||||
"eslint": "^9.26.0",
|
||||
"eslint-config-universe": "^15.0.3",
|
||||
"eslint-plugin-tsdoc": "^0.4.0",
|
||||
"ioredis": "^5.6.0",
|
||||
"jest": "^29.7.0",
|
||||
"prettier": "^3.3.3",
|
||||
"prettier": "^3.5.3",
|
||||
"prettier-plugin-organize-imports": "^4.1.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-jest": "^29.3.2",
|
||||
"ts-mockito": "^2.6.1",
|
||||
"typescript": "^5.7.3"
|
||||
"typescript": "^5.8.3"
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,13 @@ import {
|
||||
transformCacheObjectToFields,
|
||||
transformFieldsToCacheObject,
|
||||
IEntityGenericCacher,
|
||||
IEntityLoadKey,
|
||||
IEntityLoadValue,
|
||||
} from '@expo/entity';
|
||||
import invariant from 'invariant';
|
||||
|
||||
import { redisTransformerMap } from './RedisCommon';
|
||||
import wrapNativeRedisCallAsync from './errors/wrapNativeRedisCallAsync';
|
||||
import { getSurroundingCacheKeyVersionsForInvalidation } from './utils/getSurroundingCacheKeyVersionsForInvalidation';
|
||||
|
||||
// Sentinel value we store in Redis to negatively cache a database miss.
|
||||
// The sentinel value is distinct from any (positively) cached value.
|
||||
@@ -26,6 +28,24 @@ export interface IRedis {
|
||||
del(...args: [...keys: string[]]): Promise<any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The strategy for generating the set of cache keys to invalidate in the Redis cache after entity mutation.
|
||||
*/
|
||||
export enum RedisCacheInvalidationStrategy {
|
||||
/**
|
||||
* Invalidate just the cache key(s) for the current cacheKeyVersion of the entity.
|
||||
*/
|
||||
CURRENT_CACHE_KEY_VERSION = 'current-cache-key-version',
|
||||
|
||||
/**
|
||||
* Invalidate the cache key(s) for the current cacheKeyVersion and the surrounding cache key versions
|
||||
* (e.g. `1`, `2` and `3` if the current version is `2`). This can be useful for deployment safety, where
|
||||
* some machines may be operating on an old version of the code and thus an old cacheKeyVersion, and some the new version.
|
||||
* This strategy generates cache keys for both old and potential future new versions.
|
||||
*/
|
||||
SURROUNDING_CACHE_KEY_VERSIONS = 'surrounding-cache-key-versions',
|
||||
}
|
||||
|
||||
export interface GenericRedisCacheContext {
|
||||
/**
|
||||
* Instance of ioredis.Redis
|
||||
@@ -55,14 +75,21 @@ export interface GenericRedisCacheContext {
|
||||
* this TTL will be assumed not present in the database (unless invalidated).
|
||||
*/
|
||||
ttlSecondsNegative: number;
|
||||
|
||||
/**
|
||||
* Invalidation strategy for the cache.
|
||||
*/
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy;
|
||||
}
|
||||
|
||||
export default class GenericRedisCacher<TFields extends Record<string, any>>
|
||||
implements IEntityGenericCacher<TFields>
|
||||
export default class GenericRedisCacher<
|
||||
TFields extends Record<string, any>,
|
||||
TIDField extends keyof TFields,
|
||||
> implements IEntityGenericCacher<TFields, TIDField>
|
||||
{
|
||||
constructor(
|
||||
private readonly context: GenericRedisCacheContext,
|
||||
private readonly entityConfiguration: EntityConfiguration<TFields>,
|
||||
private readonly entityConfiguration: EntityConfiguration<TFields, TIDField>,
|
||||
) {}
|
||||
|
||||
public async loadManyAsync(
|
||||
@@ -147,18 +174,50 @@ export default class GenericRedisCacher<TFields extends Record<string, any>>
|
||||
await wrapNativeRedisCallAsync(() => this.context.redisClient.del(...keys));
|
||||
}
|
||||
|
||||
public makeCacheKey<N extends keyof TFields>(
|
||||
fieldName: N,
|
||||
fieldValue: NonNullable<TFields[N]>,
|
||||
): string {
|
||||
const columnName = this.entityConfiguration.entityToDBFieldsKeyMapping.get(fieldName);
|
||||
invariant(columnName, `database field mapping missing for ${String(fieldName)}`);
|
||||
private makeCacheKeyForCacheKeyVersion<
|
||||
TLoadKey extends IEntityLoadKey<TFields, TIDField, TSerializedLoadValue, TLoadValue>,
|
||||
TSerializedLoadValue,
|
||||
TLoadValue extends IEntityLoadValue<TSerializedLoadValue>,
|
||||
>(key: TLoadKey, value: TLoadValue, cacheKeyVersion: number): string {
|
||||
const cacheKeyType = key.getLoadMethodType();
|
||||
const parts = key.createCacheKeyPartsForLoadValue(this.entityConfiguration, value);
|
||||
return this.context.makeKeyFn(
|
||||
this.context.cacheKeyPrefix,
|
||||
cacheKeyType,
|
||||
this.entityConfiguration.tableName,
|
||||
`v2.${this.entityConfiguration.cacheKeyVersion}`,
|
||||
columnName,
|
||||
String(fieldValue),
|
||||
`v2.${cacheKeyVersion}`,
|
||||
...parts,
|
||||
);
|
||||
}
|
||||
|
||||
public makeCacheKeyForStorage<
|
||||
TLoadKey extends IEntityLoadKey<TFields, TIDField, TSerializedLoadValue, TLoadValue>,
|
||||
TSerializedLoadValue,
|
||||
TLoadValue extends IEntityLoadValue<TSerializedLoadValue>,
|
||||
>(key: TLoadKey, value: TLoadValue): string {
|
||||
return this.makeCacheKeyForCacheKeyVersion(
|
||||
key,
|
||||
value,
|
||||
this.entityConfiguration.cacheKeyVersion,
|
||||
);
|
||||
}
|
||||
|
||||
public makeCacheKeysForInvalidation<
|
||||
TLoadKey extends IEntityLoadKey<TFields, TIDField, TSerializedLoadValue, TLoadValue>,
|
||||
TSerializedLoadValue,
|
||||
TLoadValue extends IEntityLoadValue<TSerializedLoadValue>,
|
||||
>(key: TLoadKey, value: TLoadValue): readonly string[] {
|
||||
switch (this.context.invalidationStrategy) {
|
||||
case RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION:
|
||||
return [
|
||||
this.makeCacheKeyForCacheKeyVersion(key, value, this.entityConfiguration.cacheKeyVersion),
|
||||
];
|
||||
case RedisCacheInvalidationStrategy.SURROUNDING_CACHE_KEY_VERSIONS:
|
||||
return getSurroundingCacheKeyVersionsForInvalidation(
|
||||
this.entityConfiguration.cacheKeyVersion,
|
||||
).map((cacheKeyVersion) =>
|
||||
this.makeCacheKeyForCacheKeyVersion(key, value, cacheKeyVersion),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,9 @@ import GenericRedisCacher, { GenericRedisCacheContext } from './GenericRedisCach
|
||||
export default class RedisCacheAdapterProvider implements IEntityCacheAdapterProvider {
|
||||
constructor(private readonly context: GenericRedisCacheContext) {}
|
||||
|
||||
getCacheAdapter<TFields extends Record<string, any>>(
|
||||
entityConfiguration: EntityConfiguration<TFields>,
|
||||
): IEntityCacheAdapter<TFields> {
|
||||
getCacheAdapter<TFields extends Record<string, any>, TIDField extends keyof TFields>(
|
||||
entityConfiguration: EntityConfiguration<TFields, TIDField>,
|
||||
): IEntityCacheAdapter<TFields, TIDField> {
|
||||
return new GenericEntityCacheAdapter(new GenericRedisCacher(this.context, entityConfiguration));
|
||||
}
|
||||
}
|
||||
+48
-29
@@ -1,5 +1,11 @@
|
||||
import { Batcher } from '@expo/batcher';
|
||||
import { ViewerContext, zipToMap } from '@expo/entity';
|
||||
import {
|
||||
IEntityGenericCacher,
|
||||
SingleFieldHolder,
|
||||
SingleFieldValueHolder,
|
||||
ViewerContext,
|
||||
zipToMap,
|
||||
} from '@expo/entity';
|
||||
import invariant from 'invariant';
|
||||
import Redis from 'ioredis';
|
||||
import nullthrows from 'nullthrows';
|
||||
@@ -10,9 +16,10 @@ import GenericRedisCacher, {
|
||||
IRedis,
|
||||
IRedisTransaction,
|
||||
GenericRedisCacheContext,
|
||||
RedisCacheInvalidationStrategy,
|
||||
} from '../GenericRedisCacher';
|
||||
import RedisTestEntity from '../testfixtures/RedisTestEntity';
|
||||
import { createRedisIntegrationTestEntityCompanionProvider } from '../testfixtures/createRedisIntegrationTestEntityCompanionProvider';
|
||||
import RedisTestEntity, { RedisTestEntityFields } from '../__testfixtures__/RedisTestEntity';
|
||||
import { createRedisIntegrationTestEntityCompanionProvider } from '../__testfixtures__/createRedisIntegrationTestEntityCompanionProvider';
|
||||
|
||||
class BatchedRedis implements IRedis {
|
||||
private readonly mgetBatcher = new Batcher<string[], (string | null)[]>(
|
||||
@@ -78,6 +85,7 @@ describe(GenericRedisCacher, () => {
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -97,14 +105,14 @@ describe(GenericRedisCacher, () => {
|
||||
|
||||
const mgetSpy = jest.spyOn(redis, 'mget');
|
||||
|
||||
const genericCacher =
|
||||
viewerContext.entityCompanionProvider.getCompanionForEntity(RedisTestEntity)[
|
||||
'tableDataCoordinator'
|
||||
]['cacheAdapter']['genericCacher'];
|
||||
const cacheKeyMaker = genericCacher['makeCacheKey'].bind(genericCacher);
|
||||
const genericCacher = viewerContext.entityCompanionProvider.getCompanionForEntity(
|
||||
RedisTestEntity,
|
||||
)['tableDataCoordinator']['cacheAdapter']['genericCacher'] as IEntityGenericCacher<
|
||||
RedisTestEntityFields,
|
||||
'id'
|
||||
>;
|
||||
|
||||
const entity1Created = await RedisTestEntity.creator(viewerContext)
|
||||
.enforcing()
|
||||
.setField('name', 'blah')
|
||||
.createAsync();
|
||||
|
||||
@@ -120,11 +128,12 @@ describe(GenericRedisCacher, () => {
|
||||
createRedisIntegrationTestEntityCompanionProvider(genericRedisCacheContext),
|
||||
);
|
||||
const [entity1, entity2, entity3] = await Promise.all([
|
||||
RedisTestEntity.loader(viewerContext1).enforcing().loadByIDAsync(entity1Created.getID()),
|
||||
RedisTestEntity.loader(viewerContext2).enforcing().loadByIDAsync(entity1Created.getID()),
|
||||
RedisTestEntity.loader(viewerContext3)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', entity1Created.getField('name')),
|
||||
RedisTestEntity.loader(viewerContext1).loadByIDAsync(entity1Created.getID()),
|
||||
RedisTestEntity.loader(viewerContext2).loadByIDAsync(entity1Created.getID()),
|
||||
RedisTestEntity.loader(viewerContext3).loadByFieldEqualingAsync(
|
||||
'name',
|
||||
entity1Created.getField('name'),
|
||||
),
|
||||
]);
|
||||
|
||||
expect(mgetSpy).toHaveBeenCalledTimes(1);
|
||||
@@ -132,7 +141,10 @@ describe(GenericRedisCacher, () => {
|
||||
expect(entity1.getID()).toEqual(entity2.getID());
|
||||
expect(entity2.getID()).toEqual(nullthrows(entity3).getID());
|
||||
|
||||
const cacheKeyEntity1 = cacheKeyMaker('id', entity1Created.getID());
|
||||
const cacheKeyEntity1 = genericCacher.makeCacheKeyForStorage(
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder(entity1Created.getID()),
|
||||
);
|
||||
const cachedJSON = await redis.get(cacheKeyEntity1);
|
||||
const cachedValue = JSON.parse(cachedJSON!);
|
||||
expect(cachedValue).toMatchObject({
|
||||
@@ -140,31 +152,38 @@ describe(GenericRedisCacher, () => {
|
||||
name: 'blah',
|
||||
});
|
||||
|
||||
const cacheKeyEntity1NameField = cacheKeyMaker('name', entity1Created.getField('name'));
|
||||
await RedisTestEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', entity1Created.getField('name'));
|
||||
const cacheKeyEntity1NameField = genericCacher.makeCacheKeyForStorage(
|
||||
new SingleFieldHolder('name'),
|
||||
new SingleFieldValueHolder(entity1Created.getField('name')),
|
||||
);
|
||||
await RedisTestEntity.loader(viewerContext).loadByFieldEqualingAsync(
|
||||
'name',
|
||||
entity1Created.getField('name'),
|
||||
);
|
||||
await expect(redis.get(cacheKeyEntity1NameField)).resolves.toEqual(cachedJSON);
|
||||
|
||||
// simulate non existent db fetch, should write negative result ('') to cache
|
||||
const nonExistentId = uuidv4();
|
||||
const entityNonExistentResult = await RedisTestEntity.loader(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
.loadByIDAsync(nonExistentId);
|
||||
const entityNonExistentResult =
|
||||
await RedisTestEntity.loaderWithAuthorizationResults(viewerContext).loadByIDAsync(
|
||||
nonExistentId,
|
||||
);
|
||||
expect(entityNonExistentResult.ok).toBe(false);
|
||||
const cacheKeyNonExistent = cacheKeyMaker('id', nonExistentId);
|
||||
const cacheKeyNonExistent = genericCacher.makeCacheKeyForStorage(
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder(nonExistentId),
|
||||
);
|
||||
const nonExistentCachedValue = await redis.get(cacheKeyNonExistent);
|
||||
expect(nonExistentCachedValue).toEqual('');
|
||||
// load again through entities framework to ensure it reads negative result
|
||||
const entityNonExistentResult2 = await RedisTestEntity.loader(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
.loadByIDAsync(nonExistentId);
|
||||
const entityNonExistentResult2 =
|
||||
await RedisTestEntity.loaderWithAuthorizationResults(viewerContext).loadByIDAsync(
|
||||
nonExistentId,
|
||||
);
|
||||
expect(entityNonExistentResult2.ok).toBe(false);
|
||||
|
||||
// invalidate from cache to ensure it invalidates correctly in both caches
|
||||
await RedisTestEntity.loader(viewerContext)
|
||||
.utils()
|
||||
.invalidateFieldsAsync(entity1.getAllFields());
|
||||
await RedisTestEntity.loaderUtils(viewerContext).invalidateFieldsAsync(entity1.getAllFields());
|
||||
await expect(redis.get(cacheKeyEntity1)).resolves.toBeNull();
|
||||
await expect(redis.get(cacheKeyEntity1NameField)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
+105
-46
@@ -1,12 +1,22 @@
|
||||
import { ViewerContext } from '@expo/entity';
|
||||
import {
|
||||
CompositeFieldHolder,
|
||||
CompositeFieldValueHolder,
|
||||
IEntityGenericCacher,
|
||||
SingleFieldHolder,
|
||||
SingleFieldValueHolder,
|
||||
ViewerContext,
|
||||
} from '@expo/entity';
|
||||
import { enforceAsyncResult } from '@expo/results';
|
||||
import Redis from 'ioredis';
|
||||
import { URL } from 'url';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import GenericRedisCacher, { GenericRedisCacheContext } from '../GenericRedisCacher';
|
||||
import RedisTestEntity from '../testfixtures/RedisTestEntity';
|
||||
import { createRedisIntegrationTestEntityCompanionProvider } from '../testfixtures/createRedisIntegrationTestEntityCompanionProvider';
|
||||
import GenericRedisCacher, {
|
||||
GenericRedisCacheContext,
|
||||
RedisCacheInvalidationStrategy,
|
||||
} from '../GenericRedisCacher';
|
||||
import RedisTestEntity, { RedisTestEntityFields } from '../__testfixtures__/RedisTestEntity';
|
||||
import { createRedisIntegrationTestEntityCompanionProvider } from '../__testfixtures__/createRedisIntegrationTestEntityCompanionProvider';
|
||||
|
||||
class TestViewerContext extends ViewerContext {}
|
||||
|
||||
@@ -26,6 +36,7 @@ describe(GenericRedisCacher, () => {
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -40,58 +51,111 @@ describe(GenericRedisCacher, () => {
|
||||
const viewerContext = new TestViewerContext(
|
||||
createRedisIntegrationTestEntityCompanionProvider(genericRedisCacheContext),
|
||||
);
|
||||
const genericCacher =
|
||||
viewerContext.entityCompanionProvider.getCompanionForEntity(RedisTestEntity)[
|
||||
'tableDataCoordinator'
|
||||
]['cacheAdapter']['genericCacher'];
|
||||
const cacheKeyMaker = genericCacher['makeCacheKey'].bind(genericCacher);
|
||||
const genericCacher = viewerContext.entityCompanionProvider.getCompanionForEntity(
|
||||
RedisTestEntity,
|
||||
)['tableDataCoordinator']['cacheAdapter']['genericCacher'] as IEntityGenericCacher<
|
||||
RedisTestEntityFields,
|
||||
'id'
|
||||
>;
|
||||
|
||||
const entity1Created = await RedisTestEntity.creator(viewerContext)
|
||||
.enforcing()
|
||||
.setField('name', 'blah')
|
||||
.createAsync();
|
||||
|
||||
// loading an entity should put it in cache
|
||||
const entity1 = await RedisTestEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadByIDAsync(entity1Created.getID());
|
||||
|
||||
const cachedJSON = await (genericRedisCacheContext.redisClient as Redis).get(
|
||||
cacheKeyMaker('id', entity1.getID()),
|
||||
const entity1 = await RedisTestEntity.loader(viewerContext).loadByIDAsync(
|
||||
entity1Created.getID(),
|
||||
);
|
||||
const cachedValue = JSON.parse(cachedJSON!);
|
||||
expect(cachedValue).toMatchObject({
|
||||
|
||||
const cachedSingleJSON = await (genericRedisCacheContext.redisClient as Redis).get(
|
||||
genericCacher.makeCacheKeyForStorage(
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder(entity1.getID()),
|
||||
),
|
||||
);
|
||||
const cachedSingleValue = JSON.parse(cachedSingleJSON!);
|
||||
expect(cachedSingleValue).toMatchObject({
|
||||
id: entity1.getID(),
|
||||
name: 'blah',
|
||||
});
|
||||
|
||||
// loading an entity by composite field should put it in cache
|
||||
const entity2 = await RedisTestEntity.loader(viewerContext).loadByCompositeFieldEqualingAsync(
|
||||
['name', 'id'],
|
||||
{ name: 'blah', id: entity1.getID() },
|
||||
);
|
||||
const cachedCompositeJSON = await (genericRedisCacheContext.redisClient as Redis).get(
|
||||
genericCacher.makeCacheKeyForStorage(
|
||||
new CompositeFieldHolder<RedisTestEntityFields, 'id'>(['id', 'name']),
|
||||
new CompositeFieldValueHolder({ id: entity2!.getID(), name: 'blah' }),
|
||||
),
|
||||
);
|
||||
const cachedCompositeValue = JSON.parse(cachedCompositeJSON!);
|
||||
expect(cachedCompositeValue).toMatchObject({
|
||||
id: entity2!.getID(),
|
||||
name: 'blah',
|
||||
});
|
||||
|
||||
// simulate non existent db fetch, should write negative result ('') to cache
|
||||
const nonExistentId = uuidv4();
|
||||
|
||||
const entityNonExistentResult = await RedisTestEntity.loader(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
.loadByIDAsync(nonExistentId);
|
||||
const entityNonExistentResult =
|
||||
await RedisTestEntity.loaderWithAuthorizationResults(viewerContext).loadByIDAsync(
|
||||
nonExistentId,
|
||||
);
|
||||
expect(entityNonExistentResult.ok).toBe(false);
|
||||
|
||||
const nonExistentCachedValue = await (genericRedisCacheContext.redisClient as Redis).get(
|
||||
cacheKeyMaker('id', nonExistentId),
|
||||
genericCacher.makeCacheKeyForStorage(
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder(nonExistentId),
|
||||
),
|
||||
);
|
||||
expect(nonExistentCachedValue).toEqual('');
|
||||
|
||||
const entityNonExistentCompositeResult = await RedisTestEntity.loader(
|
||||
viewerContext,
|
||||
).loadByCompositeFieldEqualingAsync(['name', 'id'], { name: 'blah', id: nonExistentId });
|
||||
expect(entityNonExistentCompositeResult).toBe(null);
|
||||
const nonExistentCompositeCachedValue = await (
|
||||
genericRedisCacheContext.redisClient as Redis
|
||||
).get(
|
||||
genericCacher.makeCacheKeyForStorage(
|
||||
new CompositeFieldHolder<RedisTestEntityFields, 'id'>(['id', 'name']),
|
||||
new CompositeFieldValueHolder({ id: nonExistentId, name: 'blah' }),
|
||||
),
|
||||
);
|
||||
expect(nonExistentCompositeCachedValue).toEqual('');
|
||||
|
||||
// load again through entities framework to ensure it reads negative result
|
||||
const entityNonExistentResult2 = await RedisTestEntity.loader(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
.loadByIDAsync(nonExistentId);
|
||||
const entityNonExistentResult2 =
|
||||
await RedisTestEntity.loaderWithAuthorizationResults(viewerContext).loadByIDAsync(
|
||||
nonExistentId,
|
||||
);
|
||||
expect(entityNonExistentResult2.ok).toBe(false);
|
||||
const entityNonExistentCompositeResult2 = await RedisTestEntity.loader(
|
||||
viewerContext,
|
||||
).loadByCompositeFieldEqualingAsync(['name', 'id'], { name: 'blah', id: nonExistentId });
|
||||
expect(entityNonExistentCompositeResult2).toBe(null);
|
||||
|
||||
// invalidate from cache to ensure it invalidates correctly
|
||||
await RedisTestEntity.loader(viewerContext)
|
||||
.utils()
|
||||
.invalidateFieldsAsync(entity1.getAllFields());
|
||||
const cachedValueNull = await (genericRedisCacheContext.redisClient as Redis).get(
|
||||
cacheKeyMaker('id', entity1.getID()),
|
||||
await RedisTestEntity.loaderUtils(viewerContext).invalidateFieldsAsync(entity1.getAllFields());
|
||||
const cachedValueNullKeys = genericCacher.makeCacheKeysForInvalidation(
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder(entity1.getID()),
|
||||
);
|
||||
expect(cachedValueNull).toBe(null);
|
||||
const cachedValueNull = await (genericRedisCacheContext.redisClient as Redis).mget(
|
||||
...cachedValueNullKeys,
|
||||
);
|
||||
expect(cachedValueNull.every((c) => c === null)).toBe(true);
|
||||
|
||||
const cachedValueNullCompositeKeys = genericCacher.makeCacheKeysForInvalidation(
|
||||
new CompositeFieldHolder<RedisTestEntityFields, 'id'>(['id', 'name']),
|
||||
new CompositeFieldValueHolder({ id: entity1.getID(), name: 'blah' }),
|
||||
);
|
||||
const cachedValueNullComposite = await (genericRedisCacheContext.redisClient as Redis).mget(
|
||||
...cachedValueNullCompositeKeys,
|
||||
);
|
||||
expect(cachedValueNullComposite.every((c) => c === null)).toBe(true);
|
||||
});
|
||||
|
||||
it('caches and restores date fields', async () => {
|
||||
@@ -100,23 +164,20 @@ describe(GenericRedisCacher, () => {
|
||||
);
|
||||
const date = new Date();
|
||||
const entity1 = await enforceAsyncResult(
|
||||
RedisTestEntity.creator(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
RedisTestEntity.creatorWithAuthorizationResults(viewerContext)
|
||||
.setField('dateField', date)
|
||||
.createAsync(),
|
||||
);
|
||||
expect(entity1.getField('dateField')).toEqual(date);
|
||||
|
||||
const entity2 = await RedisTestEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadByIDAsync(entity1.getID());
|
||||
const entity2 = await RedisTestEntity.loader(viewerContext).loadByIDAsync(entity1.getID());
|
||||
expect(entity2.getField('dateField')).toEqual(date);
|
||||
|
||||
// simulate new request
|
||||
const vc2 = new TestViewerContext(
|
||||
createRedisIntegrationTestEntityCompanionProvider(genericRedisCacheContext),
|
||||
);
|
||||
const entity3 = await RedisTestEntity.loader(vc2).enforcing().loadByIDAsync(entity1.getID());
|
||||
const entity3 = await RedisTestEntity.loader(vc2).loadByIDAsync(entity1.getID());
|
||||
expect(entity3.getField('dateField')).toEqual(date);
|
||||
});
|
||||
|
||||
@@ -125,23 +186,21 @@ describe(GenericRedisCacher, () => {
|
||||
createRedisIntegrationTestEntityCompanionProvider(genericRedisCacheContext),
|
||||
);
|
||||
const entity1 = await enforceAsyncResult(
|
||||
RedisTestEntity.creator(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
RedisTestEntity.creatorWithAuthorizationResults(viewerContext)
|
||||
.setField('name', '')
|
||||
.createAsync(),
|
||||
);
|
||||
const entity2 = await RedisTestEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', '');
|
||||
const entity2 = await RedisTestEntity.loader(viewerContext).loadByFieldEqualingAsync(
|
||||
'name',
|
||||
'',
|
||||
);
|
||||
expect(entity2?.getID()).toEqual(entity1.getID());
|
||||
|
||||
// simulate new request
|
||||
const vc2 = new TestViewerContext(
|
||||
createRedisIntegrationTestEntityCompanionProvider(genericRedisCacheContext),
|
||||
);
|
||||
const entity3 = await RedisTestEntity.loader(vc2)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', '');
|
||||
const entity3 = await RedisTestEntity.loader(vc2).loadByFieldEqualingAsync('name', '');
|
||||
expect(entity3?.getID()).toEqual(entity1.getID());
|
||||
});
|
||||
});
|
||||
+7
-5
@@ -2,12 +2,15 @@ import { CacheStatus, ViewerContext } from '@expo/entity';
|
||||
import Redis from 'ioredis';
|
||||
import { URL } from 'url';
|
||||
|
||||
import GenericRedisCacher, { GenericRedisCacheContext } from '../GenericRedisCacher';
|
||||
import GenericRedisCacher, {
|
||||
GenericRedisCacheContext,
|
||||
RedisCacheInvalidationStrategy,
|
||||
} from '../GenericRedisCacher';
|
||||
import RedisTestEntity, {
|
||||
redisTestEntityConfiguration,
|
||||
RedisTestEntityFields,
|
||||
} from '../testfixtures/RedisTestEntity';
|
||||
import { createRedisIntegrationTestEntityCompanionProvider } from '../testfixtures/createRedisIntegrationTestEntityCompanionProvider';
|
||||
} from '../__testfixtures__/RedisTestEntity';
|
||||
import { createRedisIntegrationTestEntityCompanionProvider } from '../__testfixtures__/createRedisIntegrationTestEntityCompanionProvider';
|
||||
|
||||
class TestViewerContext extends ViewerContext {}
|
||||
|
||||
@@ -27,6 +30,7 @@ describe(GenericRedisCacher, () => {
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -47,7 +51,6 @@ describe(GenericRedisCacher, () => {
|
||||
);
|
||||
const date = new Date();
|
||||
const entity1Created = await RedisTestEntity.creator(viewerContext)
|
||||
.enforcing()
|
||||
.setField('name', 'blah')
|
||||
.setField('dateField', date)
|
||||
.createAsync();
|
||||
@@ -94,7 +97,6 @@ describe(GenericRedisCacher, () => {
|
||||
);
|
||||
const date = new Date();
|
||||
const entity1Created = await RedisTestEntity.creator(viewerContext)
|
||||
.enforcing()
|
||||
.setField('name', 'blah')
|
||||
.setField('dateField', date)
|
||||
.createAsync();
|
||||
|
||||
@@ -2,9 +2,12 @@ import { EntityCacheAdapterTransientError, ViewerContext } from '@expo/entity';
|
||||
import Redis from 'ioredis';
|
||||
import { URL } from 'url';
|
||||
|
||||
import GenericRedisCacher, { GenericRedisCacheContext } from '../GenericRedisCacher';
|
||||
import RedisTestEntity from '../testfixtures/RedisTestEntity';
|
||||
import { createRedisIntegrationTestEntityCompanionProvider } from '../testfixtures/createRedisIntegrationTestEntityCompanionProvider';
|
||||
import GenericRedisCacher, {
|
||||
GenericRedisCacheContext,
|
||||
RedisCacheInvalidationStrategy,
|
||||
} from '../GenericRedisCacher';
|
||||
import RedisTestEntity from '../__testfixtures__/RedisTestEntity';
|
||||
import { createRedisIntegrationTestEntityCompanionProvider } from '../__testfixtures__/createRedisIntegrationTestEntityCompanionProvider';
|
||||
|
||||
class TestViewerContext extends ViewerContext {}
|
||||
|
||||
@@ -25,6 +28,7 @@ describe(GenericRedisCacher, () => {
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -40,7 +44,7 @@ describe(GenericRedisCacher, () => {
|
||||
);
|
||||
|
||||
await expect(
|
||||
RedisTestEntity.creator(vc1).enforcing().setField('name', 'blah').createAsync(),
|
||||
RedisTestEntity.creator(vc1).setField('name', 'blah').createAsync(),
|
||||
).rejects.toThrow(EntityCacheAdapterTransientError);
|
||||
});
|
||||
});
|
||||
+13
-29
@@ -2,12 +2,12 @@ import {
|
||||
AlwaysAllowPrivacyPolicyRule,
|
||||
EntityPrivacyPolicy,
|
||||
ViewerContext,
|
||||
UUIDField,
|
||||
DateField,
|
||||
StringField,
|
||||
EntityConfiguration,
|
||||
EntityCompanionDefinition,
|
||||
Entity,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
|
||||
export type RedisTestEntityFields = {
|
||||
@@ -16,10 +16,10 @@ export type RedisTestEntityFields = {
|
||||
dateField: Date | null;
|
||||
};
|
||||
|
||||
export default class RedisTestEntity extends Entity<RedisTestEntityFields, string, ViewerContext> {
|
||||
export default class RedisTestEntity extends Entity<RedisTestEntityFields, 'id', ViewerContext> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
RedisTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
RedisTestEntity,
|
||||
RedisTestEntityPrivacyPolicy
|
||||
@@ -34,45 +34,25 @@ export default class RedisTestEntity extends Entity<RedisTestEntityFields, strin
|
||||
|
||||
export class RedisTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
RedisTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
RedisTestEntity
|
||||
> {
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
RedisTestEntityFields,
|
||||
string,
|
||||
ViewerContext,
|
||||
RedisTestEntity
|
||||
>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<RedisTestEntityFields, 'id', ViewerContext, RedisTestEntity>(),
|
||||
];
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
RedisTestEntityFields,
|
||||
string,
|
||||
ViewerContext,
|
||||
RedisTestEntity
|
||||
>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<RedisTestEntityFields, 'id', ViewerContext, RedisTestEntity>(),
|
||||
];
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
RedisTestEntityFields,
|
||||
string,
|
||||
ViewerContext,
|
||||
RedisTestEntity
|
||||
>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<RedisTestEntityFields, 'id', ViewerContext, RedisTestEntity>(),
|
||||
];
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
RedisTestEntityFields,
|
||||
string,
|
||||
ViewerContext,
|
||||
RedisTestEntity
|
||||
>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<RedisTestEntityFields, 'id', ViewerContext, RedisTestEntity>(),
|
||||
];
|
||||
}
|
||||
|
||||
export const redisTestEntityConfiguration = new EntityConfiguration<RedisTestEntityFields>({
|
||||
export const redisTestEntityConfiguration = new EntityConfiguration<RedisTestEntityFields, 'id'>({
|
||||
idField: 'id',
|
||||
tableName: 'redis_test_entities',
|
||||
schema: {
|
||||
@@ -90,4 +70,8 @@ export const redisTestEntityConfiguration = new EntityConfiguration<RedisTestEnt
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
compositeFieldDefinitions: [
|
||||
{ compositeField: ['id', 'name'], cache: true },
|
||||
{ compositeField: ['id', 'dateField'], cache: true },
|
||||
],
|
||||
});
|
||||
+1
-2
@@ -2,9 +2,8 @@ import {
|
||||
NoOpEntityMetricsAdapter,
|
||||
IEntityMetricsAdapter,
|
||||
EntityCompanionProvider,
|
||||
StubQueryContextProvider,
|
||||
StubDatabaseAdapterProvider,
|
||||
} from '@expo/entity';
|
||||
import { StubDatabaseAdapterProvider, StubQueryContextProvider } from '@expo/entity-testing-utils';
|
||||
|
||||
import { GenericRedisCacheContext } from '../GenericRedisCacher';
|
||||
import RedisCacheAdapterProvider from '../RedisCacheAdapterProvider';
|
||||
@@ -1,16 +1,23 @@
|
||||
import { CacheStatus, UUIDField, EntityConfiguration } from '@expo/entity';
|
||||
import {
|
||||
CacheStatus,
|
||||
EntityConfiguration,
|
||||
SingleFieldHolder,
|
||||
SingleFieldValueHolder,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
import { Redis, Pipeline } from 'ioredis';
|
||||
import { mock, when, instance, anything, verify } from 'ts-mockito';
|
||||
|
||||
import GenericRedisCacher from '../GenericRedisCacher';
|
||||
import GenericRedisCacher, { RedisCacheInvalidationStrategy } from '../GenericRedisCacher';
|
||||
|
||||
type BlahFields = {
|
||||
id: string;
|
||||
};
|
||||
|
||||
const entityConfiguration = new EntityConfiguration<BlahFields>({
|
||||
const entityConfiguration = new EntityConfiguration<BlahFields, 'id'>({
|
||||
idField: 'id',
|
||||
tableName: 'blah',
|
||||
cacheKeyVersion: 2,
|
||||
schema: {
|
||||
id: new UUIDField({ columnName: 'id', cache: true }),
|
||||
},
|
||||
@@ -37,13 +44,23 @@ describe(GenericRedisCacher, () => {
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
},
|
||||
entityConfiguration,
|
||||
);
|
||||
|
||||
const cacheKeyWat = genericCacher['makeCacheKey']('id', 'wat');
|
||||
const cacheKeyWho = genericCacher['makeCacheKey']('id', 'who');
|
||||
const cacheKeyWhy = genericCacher['makeCacheKey']('id', 'why');
|
||||
const cacheKeyWat = genericCacher['makeCacheKeyForStorage'](
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder('wat'),
|
||||
);
|
||||
const cacheKeyWho = genericCacher['makeCacheKeyForStorage'](
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder('who'),
|
||||
);
|
||||
const cacheKeyWhy = genericCacher['makeCacheKeyForStorage'](
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder('why'),
|
||||
);
|
||||
|
||||
redisResults.set(cacheKeyWat, JSON.stringify({ id: 'wat' }));
|
||||
redisResults.set(cacheKeyWho, '');
|
||||
@@ -67,6 +84,7 @@ describe(GenericRedisCacher, () => {
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
},
|
||||
entityConfiguration,
|
||||
);
|
||||
@@ -99,11 +117,15 @@ describe(GenericRedisCacher, () => {
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
},
|
||||
entityConfiguration,
|
||||
);
|
||||
|
||||
const cacheKey = genericCacher['makeCacheKey']('id', 'wat');
|
||||
const cacheKey = genericCacher['makeCacheKeyForStorage'](
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder('wat'),
|
||||
);
|
||||
|
||||
await genericCacher.cacheManyAsync(new Map([[cacheKey, { id: 'wat' }]]));
|
||||
|
||||
@@ -138,11 +160,15 @@ describe(GenericRedisCacher, () => {
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
},
|
||||
entityConfiguration,
|
||||
);
|
||||
|
||||
const cacheKey = genericCacher['makeCacheKey']('id', 'wat');
|
||||
const cacheKey = genericCacher['makeCacheKeyForStorage'](
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder('wat'),
|
||||
);
|
||||
|
||||
await genericCacher.cacheDBMissesAsync([cacheKey]);
|
||||
|
||||
@@ -155,7 +181,7 @@ describe(GenericRedisCacher, () => {
|
||||
});
|
||||
|
||||
describe('invalidateManyAsync', () => {
|
||||
it('invalidates correctly', async () => {
|
||||
it('invalidates correctly with RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION', async () => {
|
||||
const mockRedisClient = mock<Redis>();
|
||||
when(mockRedisClient.del()).thenResolve(1);
|
||||
|
||||
@@ -166,14 +192,43 @@ describe(GenericRedisCacher, () => {
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
},
|
||||
entityConfiguration,
|
||||
);
|
||||
const cacheKey = genericCacher['makeCacheKey']('id', 'wat');
|
||||
const cacheKeys = genericCacher['makeCacheKeysForInvalidation'](
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder('wat'),
|
||||
);
|
||||
expect(cacheKeys).toHaveLength(1);
|
||||
|
||||
await genericCacher.invalidateManyAsync([cacheKey]);
|
||||
await genericCacher.invalidateManyAsync(cacheKeys);
|
||||
verify(mockRedisClient.del(...cacheKeys)).once();
|
||||
});
|
||||
|
||||
verify(mockRedisClient.del(cacheKey)).once();
|
||||
it('invalidates correctly with RedisCacheInvalidationStrategy.SURROUNDING_CACHE_KEY_VERSIONS', async () => {
|
||||
const mockRedisClient = mock<Redis>();
|
||||
when(mockRedisClient.del()).thenResolve(1);
|
||||
|
||||
const genericCacher = new GenericRedisCacher(
|
||||
{
|
||||
redisClient: instance(mockRedisClient),
|
||||
makeKeyFn: (...parts) => parts.join(':'),
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.SURROUNDING_CACHE_KEY_VERSIONS,
|
||||
},
|
||||
entityConfiguration,
|
||||
);
|
||||
const cacheKeys = genericCacher['makeCacheKeysForInvalidation'](
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder('wat'),
|
||||
);
|
||||
expect(cacheKeys).toHaveLength(3);
|
||||
|
||||
await genericCacher.invalidateManyAsync(cacheKeys);
|
||||
verify(mockRedisClient.del(...cacheKeys)).once();
|
||||
});
|
||||
|
||||
it('returns when passed empty array of fieldValues', async () => {
|
||||
@@ -184,6 +239,7 @@ describe(GenericRedisCacher, () => {
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
},
|
||||
entityConfiguration,
|
||||
);
|
||||
|
||||
@@ -9,3 +9,4 @@ export * from './GenericRedisCacher';
|
||||
export { default as RedisCacheAdapterProvider } from './RedisCacheAdapterProvider';
|
||||
export * from './RedisCommon';
|
||||
export { default as wrapNativeRedisCallAsync } from './errors/wrapNativeRedisCallAsync';
|
||||
export * from './utils/getSurroundingCacheKeyVersionsForInvalidation';
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import { getSurroundingCacheKeyVersionsForInvalidation } from '../getSurroundingCacheKeyVersionsForInvalidation';
|
||||
|
||||
describe(getSurroundingCacheKeyVersionsForInvalidation, () => {
|
||||
it('returns the correct cache key versions to invalidate', () => {
|
||||
expect(getSurroundingCacheKeyVersionsForInvalidation(0)).toEqual([0, 1]);
|
||||
expect(getSurroundingCacheKeyVersionsForInvalidation(1)).toEqual([0, 1, 2]);
|
||||
expect(getSurroundingCacheKeyVersionsForInvalidation(2)).toEqual([1, 2, 3]);
|
||||
});
|
||||
});
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
export function getSurroundingCacheKeyVersionsForInvalidation(
|
||||
cacheKeyVersion: number,
|
||||
): readonly number[] {
|
||||
return [
|
||||
...(cacheKeyVersion === 0 ? [] : [cacheKeyVersion - 1]),
|
||||
cacheKeyVersion,
|
||||
cacheKeyVersion + 1,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.build.json",
|
||||
"include": ["src"],
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "build",
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
**/__testfixtures__/**
|
||||
@@ -3,6 +3,41 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.44.0](https://github.com/expo/entity/compare/v0.43.0...v0.44.0) (2025-05-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-codemod
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.43.0](https://github.com/expo/entity/compare/v0.42.0...v0.43.0) (2025-04-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-codemod
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.42.0](https://github.com/expo/entity/compare/v0.41.0...v0.42.0) (2025-04-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-codemod
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.41.0](https://github.com/expo/entity/compare/v0.40.0...v0.41.0) (2025-03-07)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Create codemod for v0.40.0 -> v0.41.0 ([#260](https://github.com/expo/entity/issues/260)) ([4a2b61f](https://github.com/expo/entity/commit/4a2b61f2bd8edfc19109ef4c8ac780eaf0f7795c))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.40.0](https://github.com/expo/entity/compare/v0.39.0...v0.40.0) (2025-02-27)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity-codemod",
|
||||
"version": "0.40.0",
|
||||
"version": "0.44.0",
|
||||
"description": "jscodeshift codemods for @expo/entity upgrades",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -10,6 +10,7 @@
|
||||
"types": "build/index.d.ts",
|
||||
"scripts": {
|
||||
"tsc": "tsc",
|
||||
"build": "tsc -b tsconfig.build.json",
|
||||
"clean": "rm -rf build coverage coverage-integration",
|
||||
"lint": "eslint src",
|
||||
"lint-fix": "eslint src --fix",
|
||||
@@ -24,17 +25,17 @@
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/jscodeshift": "^0.12.0",
|
||||
"@types/node": "^20.14.1",
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-config-universe": "^14.0.0",
|
||||
"eslint-plugin-tsdoc": "^0.3.0",
|
||||
"eslint": "^9.26.0",
|
||||
"eslint-config-universe": "^15.0.3",
|
||||
"eslint-plugin-tsdoc": "^0.4.0",
|
||||
"jest": "^29.7.0",
|
||||
"jscodeshift": "^17.1.2",
|
||||
"prettier": "^3.3.3",
|
||||
"ts-jest": "^29.2.5",
|
||||
"jscodeshift": "^17.3.0",
|
||||
"prettier": "^3.5.3",
|
||||
"ts-jest": "^29.3.2",
|
||||
"ts-mockito": "^2.6.1",
|
||||
"typescript": "^5.7.3"
|
||||
"typescript": "^5.8.3"
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
/* eslint-disable */
|
||||
|
||||
import { ViewerContext } from '@expo/entity';
|
||||
|
||||
async function testWithAuthorizationResults(viewerContext: ViewerContext): Promise<void> {
|
||||
// creator
|
||||
const entityResult = await TestEntity.creator(viewerContext).withAuthorizationResults().setField('wat', 2).createAsync();
|
||||
|
||||
// updater
|
||||
const updatedEntityResult = await TestEntity.updater(entityResult.enforceValue()).withAuthorizationResults().setField('wat', 3).updateAsync();
|
||||
|
||||
// loader
|
||||
const loadedEntityResult = await TestEntity.loader(viewerContext).withAuthorizationResults().loadByIDAsync('test');
|
||||
|
||||
// deleter
|
||||
await TestEntity.deleter(updatedEntityResult.enforceValue()).withAuthorizationResults().deleteAsync();
|
||||
}
|
||||
|
||||
async function testEnforcing(viewerContext: ViewerContext): Promise<void> {
|
||||
// creator
|
||||
const entity = await TestEntity.creator(viewerContext).enforcing().setField('wat', 2).createAsync();
|
||||
const entity2 = await TestEntity.creator(viewerContext).enforcing().setField('wat', 2).setField('who', 3).createAsync();
|
||||
const entity3 = await TestEntity.creator(viewerContext).enforcing()
|
||||
.setField('wat', 2)
|
||||
.setField('who', 3)
|
||||
.setField('who', 4)
|
||||
.setField('who', 5)
|
||||
.setField('who', 6)
|
||||
.setField('who', 7)
|
||||
.setField('who', 8)
|
||||
.setField('who', 9)
|
||||
.createAsync();
|
||||
|
||||
// updater
|
||||
const updatedEntity = await TestEntity.updater(entity).enforcing().setField('wat', 3).updateAsync();
|
||||
const updatedEntity2 = await TestEntity.updater(entity2).enforcing().setField('wat', 3).setField('who', 4).updateAsync();
|
||||
const updatedEntity3 = await TestEntity.updater(entity3).enforcing()
|
||||
.setField('wat', 3)
|
||||
.setField('who', 4)
|
||||
.setField('who', 5)
|
||||
.setField('who', 6)
|
||||
.setField('who', 7)
|
||||
.setField('who', 8)
|
||||
.setField('who', 9)
|
||||
.updateAsync();
|
||||
|
||||
// loader
|
||||
const loadedEntity = await TestEntity.loader(viewerContext).enforcing().loadByIDAsync('test');
|
||||
|
||||
// deleter
|
||||
await TestEntity.deleter(entity).enforcing().deleteAsync();
|
||||
}
|
||||
|
||||
async function testNoSetField(viewerContext: ViewerContext): Promise<void> {
|
||||
// creator
|
||||
const entity = await TestEntity.creator(viewerContext).enforcing().createAsync();
|
||||
|
||||
// updater
|
||||
const updatedEntity = await TestEntity.updater(entity).enforcing().updateAsync();
|
||||
}
|
||||
|
||||
async function testEnforcingWithQueryContext(viewerContext: ViewerContext): Promise<void> {
|
||||
// creator
|
||||
const entity = await TestEntity.creator(viewerContext, queryContext).enforcing().setField('wat', 2).createAsync();
|
||||
|
||||
// updater
|
||||
const updatedEntity = await TestEntity.updater(entity, queryContext).enforcing().setField('wat', 3).updateAsync();
|
||||
|
||||
// loader
|
||||
const loadedEntity = await TestEntity.loader(viewerContext, queryContext).enforcing().loadByIDAsync('test');
|
||||
|
||||
// deleter
|
||||
await TestEntity.deleter(entity, queryContext).enforcing().deleteAsync();
|
||||
}
|
||||
|
||||
async function testAssociationLoader(): Promise<void> {
|
||||
await this.associationLoader().withAuthorizationResults().loadAssociatedEntityAsync(
|
||||
'another_id',
|
||||
AnotherEntity,
|
||||
queryContext
|
||||
);
|
||||
|
||||
await entity.associationLoader().withAuthorizationResults().loadAssociatedEntityAsync(
|
||||
'another_id',
|
||||
AnotherEntity,
|
||||
queryContext
|
||||
)
|
||||
|
||||
await this.associationLoader().enforcing().loadAssociatedEntityAsync(
|
||||
'another_id',
|
||||
AnotherEntity,
|
||||
queryContext
|
||||
);
|
||||
|
||||
await entity.associationLoader().enforcing().loadAssociatedEntityAsync(
|
||||
'another_id',
|
||||
AnotherEntity,
|
||||
queryContext
|
||||
)
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
/* eslint-disable */
|
||||
|
||||
import { ViewerContext } from '@expo/entity';
|
||||
|
||||
async function testWithAuthorizationResults(viewerContext: ViewerContext): Promise<void> {
|
||||
// creator
|
||||
const entityResult = await TestEntity.creatorWithAuthorizationResults(viewerContext).setField('wat', 2).createAsync();
|
||||
|
||||
// updater
|
||||
const updatedEntityResult = await TestEntity.updaterWithAuthorizationResults(entityResult.enforceValue()).setField('wat', 3).updateAsync();
|
||||
|
||||
// loader
|
||||
const loadedEntityResult = await TestEntity.loaderWithAuthorizationResults(viewerContext).loadByIDAsync('test');
|
||||
|
||||
// deleter
|
||||
await TestEntity.deleterWithAuthorizationResults(updatedEntityResult.enforceValue()).deleteAsync();
|
||||
}
|
||||
|
||||
async function testEnforcing(viewerContext: ViewerContext): Promise<void> {
|
||||
// creator
|
||||
const entity = await TestEntity.creator(viewerContext).setField('wat', 2).createAsync();
|
||||
const entity2 = await TestEntity.creator(viewerContext).setField('wat', 2).setField('who', 3).createAsync();
|
||||
const entity3 = await TestEntity.creator(viewerContext)
|
||||
.setField('wat', 2)
|
||||
.setField('who', 3)
|
||||
.setField('who', 4)
|
||||
.setField('who', 5)
|
||||
.setField('who', 6)
|
||||
.setField('who', 7)
|
||||
.setField('who', 8)
|
||||
.setField('who', 9)
|
||||
.createAsync();
|
||||
|
||||
// updater
|
||||
const updatedEntity = await TestEntity.updater(entity).setField('wat', 3).updateAsync();
|
||||
const updatedEntity2 = await TestEntity.updater(entity2).setField('wat', 3).setField('who', 4).updateAsync();
|
||||
const updatedEntity3 = await TestEntity.updater(entity3)
|
||||
.setField('wat', 3)
|
||||
.setField('who', 4)
|
||||
.setField('who', 5)
|
||||
.setField('who', 6)
|
||||
.setField('who', 7)
|
||||
.setField('who', 8)
|
||||
.setField('who', 9)
|
||||
.updateAsync();
|
||||
|
||||
// loader
|
||||
const loadedEntity = await TestEntity.loader(viewerContext).loadByIDAsync('test');
|
||||
|
||||
// deleter
|
||||
await TestEntity.deleter(entity).deleteAsync();
|
||||
}
|
||||
|
||||
async function testNoSetField(viewerContext: ViewerContext): Promise<void> {
|
||||
// creator
|
||||
const entity = await TestEntity.creator(viewerContext).createAsync();
|
||||
|
||||
// updater
|
||||
const updatedEntity = await TestEntity.updater(entity).updateAsync();
|
||||
}
|
||||
|
||||
async function testEnforcingWithQueryContext(viewerContext: ViewerContext): Promise<void> {
|
||||
// creator
|
||||
const entity = await TestEntity.creator(viewerContext, queryContext).setField('wat', 2).createAsync();
|
||||
|
||||
// updater
|
||||
const updatedEntity = await TestEntity.updater(entity, queryContext).setField('wat', 3).updateAsync();
|
||||
|
||||
// loader
|
||||
const loadedEntity = await TestEntity.loader(viewerContext, queryContext).loadByIDAsync('test');
|
||||
|
||||
// deleter
|
||||
await TestEntity.deleter(entity, queryContext).deleteAsync();
|
||||
}
|
||||
|
||||
async function testAssociationLoader(): Promise<void> {
|
||||
await this.associationLoaderWithAuthorizationResults().loadAssociatedEntityAsync(
|
||||
'another_id',
|
||||
AnotherEntity,
|
||||
queryContext
|
||||
);
|
||||
|
||||
await entity.associationLoaderWithAuthorizationResults().loadAssociatedEntityAsync(
|
||||
'another_id',
|
||||
AnotherEntity,
|
||||
queryContext
|
||||
)
|
||||
|
||||
await this.associationLoader().loadAssociatedEntityAsync(
|
||||
'another_id',
|
||||
AnotherEntity,
|
||||
queryContext
|
||||
);
|
||||
|
||||
await entity.associationLoader().loadAssociatedEntityAsync(
|
||||
'another_id',
|
||||
AnotherEntity,
|
||||
queryContext
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { readdirSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
jest.autoMockOff();
|
||||
const defineTest = require('jscodeshift/dist/testUtils').defineTest;
|
||||
|
||||
const fixtureDir = 'v0.40.0-v0.41.0';
|
||||
const fixtureDirPath = join(__dirname, '..', '__testfixtures__', fixtureDir);
|
||||
const fixtures = readdirSync(fixtureDirPath)
|
||||
.filter((file) => file.endsWith('.input.ts'))
|
||||
.map((file) => file.replace('.input.ts', ''));
|
||||
|
||||
for (const fixture of fixtures) {
|
||||
const prefix = `${fixtureDir}/${fixture}`;
|
||||
defineTest(__dirname, 'v0.40.0-v0.41.0', null, prefix, { parser: 'ts' });
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { API, Collection, FileInfo, Options } from 'jscodeshift';
|
||||
|
||||
function transformWithAuthorizationResultsEntityChainMethod(
|
||||
j: API['jscodeshift'],
|
||||
root: Collection<any>,
|
||||
): void {
|
||||
// Find all entity expressions of the form
|
||||
// `TestEntity.thing(viewerContext).withAuthorizationResults()`
|
||||
root
|
||||
.find(j.CallExpression, {
|
||||
callee: {
|
||||
type: 'MemberExpression',
|
||||
property: {
|
||||
name: 'withAuthorizationResults',
|
||||
},
|
||||
},
|
||||
})
|
||||
.forEach((path) => {
|
||||
const withAuthorizationResultsCallExpression = path.node; // TestEntity.thing(viewerContext).withAuthorizationResults()
|
||||
const withAuthorizationResultsCallee = withAuthorizationResultsCallExpression.callee; // TestEntity.thing(viewerContext).withAuthorizationResults
|
||||
if (withAuthorizationResultsCallee.type !== 'MemberExpression') {
|
||||
return;
|
||||
}
|
||||
|
||||
const thingCallExpression = withAuthorizationResultsCallee.object; // TestEntity.thing(viewerContext)
|
||||
if (thingCallExpression.type !== 'CallExpression') {
|
||||
return;
|
||||
}
|
||||
const thingCallee = thingCallExpression.callee; // TestEntity.thing
|
||||
if (thingCallee.type !== 'MemberExpression') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (thingCallee.property.type !== 'Identifier') {
|
||||
return;
|
||||
}
|
||||
|
||||
const newCreatorCalleeName = thingCallee.property.name + 'WithAuthorizationResults';
|
||||
thingCallee.property.name = newCreatorCalleeName;
|
||||
|
||||
path.replace(thingCallExpression);
|
||||
});
|
||||
}
|
||||
|
||||
function transformEnforcingEntityChainMethod(j: API['jscodeshift'], root: Collection<any>): void {
|
||||
// Find all entity expressions of the form
|
||||
// `TestEntity.thing(viewerContext).enforcing()`
|
||||
root
|
||||
.find(j.CallExpression, {
|
||||
callee: {
|
||||
type: 'MemberExpression',
|
||||
property: {
|
||||
name: 'enforcing',
|
||||
},
|
||||
},
|
||||
})
|
||||
.forEach((path) => {
|
||||
const enforcingCallExpression = path.node; // TestEntity.thing(viewerContext).enforcing()
|
||||
const enforcingCallee = enforcingCallExpression.callee; // TestEntity.thing(viewerContext).enforcing
|
||||
if (enforcingCallee.type !== 'MemberExpression') {
|
||||
return;
|
||||
}
|
||||
|
||||
const thingCallExpression = enforcingCallee.object; // TestEntity.thing(viewerContext)
|
||||
if (thingCallExpression.type !== 'CallExpression') {
|
||||
return;
|
||||
}
|
||||
|
||||
path.replace(thingCallExpression);
|
||||
});
|
||||
}
|
||||
|
||||
export default function transformer(file: FileInfo, api: API, _options: Options): string {
|
||||
const j = api.jscodeshift;
|
||||
const root = j.withParser('ts')(file.source);
|
||||
|
||||
transformWithAuthorizationResultsEntityChainMethod(j, root);
|
||||
transformEnforcingEntityChainMethod(j, root);
|
||||
|
||||
return root.toSource();
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.build.json",
|
||||
"exclude": ["**/__testfixtures__/**"]
|
||||
}
|
||||
@@ -1,8 +1,5 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "build",
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["**/__testfixtures__/**"]
|
||||
"exclude": ["**/__testfixtures__/**"],
|
||||
}
|
||||
@@ -3,6 +3,59 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.44.0](https://github.com/expo/entity/compare/v0.43.0...v0.44.0) (2025-05-29)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* introduce transactional dataloader mode and fix global transaction ID generation ([#289](https://github.com/expo/entity/issues/289)) ([d3e89bd](https://github.com/expo/entity/commit/d3e89bdd82e6df5c5b35522bc3574fd9e1cfddff))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add transaction-scoped dataloaders ([#284](https://github.com/expo/entity/issues/284)) ([e054a0d](https://github.com/expo/entity/commit/e054a0d74b3a39158ca7d73d05f59d3633113400)), closes [#98](https://github.com/expo/entity/issues/98) [#194](https://github.com/expo/entity/issues/194)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.43.0](https://github.com/expo/entity/compare/v0.42.0...v0.43.0) (2025-04-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-database-adapter-knex
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.42.0](https://github.com/expo/entity/compare/v0.41.0...v0.42.0) (2025-04-10)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add @expo/entity-testing-utils package ([#280](https://github.com/expo/entity/issues/280)) ([485894a](https://github.com/expo/entity/commit/485894af16e233d533a9480285bbda56812cbe0b))
|
||||
* add composite field loading and caching ([#272](https://github.com/expo/entity/issues/272)) ([f0aa0da](https://github.com/expo/entity/commit/f0aa0dafebdb56418cbd22dda437233d850db3e7))
|
||||
* change entity id field generic to field name and derive type where necessary ([#278](https://github.com/expo/entity/issues/278)) ([b7e524c](https://github.com/expo/entity/commit/b7e524c41892797608d0b884410b8d520a80a9ef))
|
||||
* convert batched/cached loader interface to holder pattern ([#271](https://github.com/expo/entity/issues/271)) ([06b3cb7](https://github.com/expo/entity/commit/06b3cb7f8076ef9e5b83cdf154da159801bd14cc)), closes [#201](https://github.com/expo/entity/issues/201)
|
||||
* enforce explicit id field cache property ([#276](https://github.com/expo/entity/issues/276)) ([1da5cc0](https://github.com/expo/entity/commit/1da5cc01e1affc3b3338a0ab2050504b5853ac6f))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.41.0](https://github.com/expo/entity/compare/v0.40.0...v0.41.0) (2025-03-07)
|
||||
|
||||
|
||||
* feat!: Default all loaders and mutators to enforcing (#256) ([a976e76](https://github.com/expo/entity/commit/a976e765098bca27049585e43a3bed5c71b9ac6b)), closes [#256](https://github.com/expo/entity/issues/256)
|
||||
|
||||
|
||||
### BREAKING CHANGES
|
||||
|
||||
* Default all loaders and mutators to enforcing
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.40.0](https://github.com/expo/entity/compare/v0.39.0...v0.40.0) (2025-02-27)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity-database-adapter-knex",
|
||||
"version": "0.40.0",
|
||||
"version": "0.44.0",
|
||||
"description": "Knex database adapter for @expo/entity",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -10,6 +10,7 @@
|
||||
"types": "build/index.d.ts",
|
||||
"scripts": {
|
||||
"tsc": "tsc",
|
||||
"build": "tsc -b tsconfig.build.json",
|
||||
"clean": "rm -rf build coverage coverage-integration",
|
||||
"lint": "eslint src",
|
||||
"lint-fix": "eslint src --fix",
|
||||
@@ -31,18 +32,19 @@
|
||||
"knex": "^3.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.12",
|
||||
"@expo/entity-testing-utils": "workspace:^",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^20.14.1",
|
||||
"ctix": "^2.7.0",
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-config-universe": "^14.0.0",
|
||||
"eslint-plugin-tsdoc": "^0.3.0",
|
||||
"eslint": "^9.26.0",
|
||||
"eslint-config-universe": "^15.0.3",
|
||||
"eslint-plugin-tsdoc": "^0.4.0",
|
||||
"jest": "^29.7.0",
|
||||
"pg": "8.13.1",
|
||||
"prettier": "^3.3.3",
|
||||
"pg": "8.14.1",
|
||||
"prettier": "^3.5.3",
|
||||
"prettier-plugin-organize-imports": "^4.1.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-jest": "^29.3.2",
|
||||
"ts-mockito": "^2.6.1",
|
||||
"typescript": "^5.7.3"
|
||||
"typescript": "^5.8.3"
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,10 @@ import { EntityFieldDefinition } from '@expo/entity';
|
||||
/**
|
||||
* EntityFieldDefinition for a Postres column with a JS JSON array type.
|
||||
*/
|
||||
export class JSONArrayField extends EntityFieldDefinition<any[]> {
|
||||
export class JSONArrayField<TRequireExplicitCache extends boolean> extends EntityFieldDefinition<
|
||||
any[],
|
||||
TRequireExplicitCache
|
||||
> {
|
||||
protected validateInputValueInternal(value: any[]): boolean {
|
||||
return Array.isArray(value);
|
||||
}
|
||||
@@ -13,7 +16,9 @@ export class JSONArrayField extends EntityFieldDefinition<any[]> {
|
||||
* EntityFieldDefinition for a Postgres column that may be a JS JSON array type.
|
||||
* Does not do any validation.
|
||||
*/
|
||||
export class MaybeJSONArrayField extends EntityFieldDefinition<any | any[]> {
|
||||
export class MaybeJSONArrayField<
|
||||
TRequireExplicitCache extends boolean,
|
||||
> extends EntityFieldDefinition<any | any[], TRequireExplicitCache> {
|
||||
protected validateInputValueInternal(_value: any): boolean {
|
||||
return true;
|
||||
}
|
||||
@@ -22,7 +27,10 @@ export class MaybeJSONArrayField extends EntityFieldDefinition<any | any[]> {
|
||||
/**
|
||||
* EntityFieldDefinition for a Postgres BIGINT column.
|
||||
*/
|
||||
export class BigIntField extends EntityFieldDefinition<string> {
|
||||
export class BigIntField<TRequireExplicitCache extends boolean> extends EntityFieldDefinition<
|
||||
string,
|
||||
TRequireExplicitCache
|
||||
> {
|
||||
protected validateInputValueInternal(value: string): boolean {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
|
||||
@@ -14,7 +14,8 @@ import wrapNativePostgresCallAsync from './errors/wrapNativePostgresCallAsync';
|
||||
|
||||
export default class PostgresEntityDatabaseAdapter<
|
||||
TFields extends Record<string, any>,
|
||||
> extends EntityDatabaseAdapter<TFields> {
|
||||
TIDField extends keyof TFields,
|
||||
> extends EntityDatabaseAdapter<TFields, TIDField> {
|
||||
protected getFieldTransformerMap(): FieldTransformerMap {
|
||||
return new Map<string, FieldTransformer<any>>([
|
||||
[
|
||||
@@ -44,14 +45,44 @@ export default class PostgresEntityDatabaseAdapter<
|
||||
protected async fetchManyWhereInternalAsync(
|
||||
queryInterface: Knex,
|
||||
tableName: string,
|
||||
tableField: string,
|
||||
tableValues: readonly any[],
|
||||
tableColumns: readonly string[],
|
||||
tableTuples: any[][],
|
||||
): Promise<object[]> {
|
||||
// For single column queries, use the ANY operator to derive a consistent
|
||||
// query shape in the postgres query stats table.
|
||||
// This produces a query of the form `SELECT * FROM table WHERE ("id") = ANY(?)`
|
||||
// with value bindings of the form `[[1]]`, thus not making different value cardinalities
|
||||
// produce different query shapes.
|
||||
//
|
||||
// But for multi-column queries, we must use the IN operator as the ANY operator
|
||||
// does not support anonymous composite types. The solution to keep using the ANY operator would be explicit
|
||||
// postgres type casting on each value in each tableTuple, thus creating a unique query shape and defeating the purpose.
|
||||
// The same applies to using UNNEST on anonymous composite types.
|
||||
// Note that this solution is not possible in entity though since we don't have the postgres column types and they
|
||||
// can't be derived dynamically.
|
||||
//
|
||||
// Therefore, for multi-column quries, we use the IN operator which produces a query of the form
|
||||
// `SELECT * FROM table WHERE ("id", "name") IN ((?, ?), (?, ?))` with value bindings of the form
|
||||
// `[[1, 'a'], [2, 'b']]`, which will produce a unique query shape in the postgres query stats table for
|
||||
// each value cardinality.
|
||||
//
|
||||
// We could use the IN operator for single column queries as well, but we prefer to use ANY to at least keep some
|
||||
// consistency in the query shape for the stats table.
|
||||
|
||||
if (tableColumns.length === 1) {
|
||||
return await wrapNativePostgresCallAsync(() =>
|
||||
queryInterface
|
||||
.select()
|
||||
.from(tableName)
|
||||
.whereRaw(`(??) = ANY(?)`, [
|
||||
tableColumns[0],
|
||||
tableTuples.map((tableTuple) => tableTuple[0]),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
return await wrapNativePostgresCallAsync(() =>
|
||||
queryInterface
|
||||
.select()
|
||||
.from(tableName)
|
||||
.whereRaw('?? = ANY(?)', [tableField, tableValues as any[]]),
|
||||
queryInterface.select().from(tableName).whereIn(tableColumns, tableTuples),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,9 +9,9 @@ import PostgresEntityDatabaseAdapter from './PostgresEntityDatabaseAdapter';
|
||||
export default class PostgresEntityDatabaseAdapterProvider
|
||||
implements IEntityDatabaseAdapterProvider
|
||||
{
|
||||
getDatabaseAdapter<TFields extends Record<string, any>>(
|
||||
entityConfiguration: EntityConfiguration<TFields>,
|
||||
): EntityDatabaseAdapter<TFields> {
|
||||
getDatabaseAdapter<TFields extends Record<string, any>, TIDField extends keyof TFields>(
|
||||
entityConfiguration: EntityConfiguration<TFields, TIDField>,
|
||||
): EntityDatabaseAdapter<TFields, TIDField> {
|
||||
return new PostgresEntityDatabaseAdapter(entityConfiguration);
|
||||
}
|
||||
}
|
||||
+209
-250
@@ -1,18 +1,14 @@
|
||||
import {
|
||||
OrderByOrdering,
|
||||
createUnitTestEntityCompanionProvider,
|
||||
ViewerContext,
|
||||
TransactionIsolationLevel,
|
||||
} from '@expo/entity';
|
||||
import { OrderByOrdering, ViewerContext, TransactionIsolationLevel } from '@expo/entity';
|
||||
import { createUnitTestEntityCompanionProvider } from '@expo/entity-testing-utils';
|
||||
import { enforceAsyncResult } from '@expo/results';
|
||||
import { knex, Knex } from 'knex';
|
||||
import nullthrows from 'nullthrows';
|
||||
import { setTimeout } from 'timers/promises';
|
||||
|
||||
import PostgresTestEntity from '../testfixtures/PostgresTestEntity';
|
||||
import PostgresTriggerTestEntity from '../testfixtures/PostgresTriggerTestEntity';
|
||||
import PostgresValidatorTestEntity from '../testfixtures/PostgresValidatorTestEntity';
|
||||
import { createKnexIntegrationTestEntityCompanionProvider } from '../testfixtures/createKnexIntegrationTestEntityCompanionProvider';
|
||||
import PostgresTestEntity from '../__testfixtures__/PostgresTestEntity';
|
||||
import PostgresTriggerTestEntity from '../__testfixtures__/PostgresTriggerTestEntity';
|
||||
import PostgresValidatorTestEntity from '../__testfixtures__/PostgresValidatorTestEntity';
|
||||
import { createKnexIntegrationTestEntityCompanionProvider } from '../__testfixtures__/createKnexIntegrationTestEntityCompanionProvider';
|
||||
|
||||
describe('postgres entity integration', () => {
|
||||
let knexInstance: Knex;
|
||||
@@ -42,21 +38,18 @@ describe('postgres entity integration', () => {
|
||||
it('supports parallel partial updates', async () => {
|
||||
const vc = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc)
|
||||
.setField('name', 'hello')
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
// update two different fields at the same time (from the same entity)
|
||||
await Promise.all([
|
||||
PostgresTestEntity.updater(entity).enforcing().setField('hasACat', true).updateAsync(),
|
||||
PostgresTestEntity.updater(entity).enforcing().setField('hasADog', false).updateAsync(),
|
||||
PostgresTestEntity.updater(entity).setField('hasACat', true).updateAsync(),
|
||||
PostgresTestEntity.updater(entity).setField('hasADog', false).updateAsync(),
|
||||
]);
|
||||
|
||||
const loadedEntity = await PostgresTestEntity.loader(vc)
|
||||
.enforcing()
|
||||
.loadByIDAsync(entity.getID());
|
||||
const loadedEntity = await PostgresTestEntity.loader(vc).loadByIDAsync(entity.getID());
|
||||
|
||||
expect(loadedEntity.getField('hasACat')).toBe(true);
|
||||
expect(loadedEntity.getField('hasADog')).toBe(false);
|
||||
@@ -66,7 +59,7 @@ describe('postgres entity integration', () => {
|
||||
it('allows empty create', async () => {
|
||||
const vc = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc).withAuthorizationResults().createAsync(),
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc).createAsync(),
|
||||
);
|
||||
expect(entity.getID()).toBeTruthy();
|
||||
});
|
||||
@@ -74,23 +67,21 @@ describe('postgres entity integration', () => {
|
||||
it('throws knex error upon empty update', async () => {
|
||||
const vc = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc)
|
||||
.setField('name', 'hello')
|
||||
.createAsync(),
|
||||
);
|
||||
await expect(PostgresTestEntity.updater(entity).enforcing().updateAsync()).rejects.toThrow();
|
||||
await expect(PostgresTestEntity.updater(entity).updateAsync()).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('throws error upon empty update for stub database adapter to match behavior', async () => {
|
||||
const vc = new ViewerContext(createUnitTestEntityCompanionProvider());
|
||||
const entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc)
|
||||
.setField('name', 'hello')
|
||||
.createAsync(),
|
||||
);
|
||||
await expect(PostgresTestEntity.updater(entity).enforcing().updateAsync()).rejects.toThrow();
|
||||
await expect(PostgresTestEntity.updater(entity).updateAsync()).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -99,13 +90,12 @@ describe('postgres entity integration', () => {
|
||||
|
||||
// put one in the DB
|
||||
const firstEntity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'hello')
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await PostgresTestEntity.loader(vc1).enforcing().loadByIDAsync(firstEntity.getID());
|
||||
await PostgresTestEntity.loader(vc1).loadByIDAsync(firstEntity.getID());
|
||||
|
||||
const errorToThrow = new Error('Intentional error');
|
||||
|
||||
@@ -115,8 +105,7 @@ describe('postgres entity integration', () => {
|
||||
async (queryContext) => {
|
||||
// put another in the DB that will be rolled back due to error thrown
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1, queryContext)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1, queryContext)
|
||||
.setField('name', 'hello')
|
||||
.createAsync(),
|
||||
);
|
||||
@@ -127,9 +116,10 @@ describe('postgres entity integration', () => {
|
||||
),
|
||||
).rejects.toEqual(errorToThrow);
|
||||
|
||||
const entities = await PostgresTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadManyByFieldEqualingAsync('name', 'hello');
|
||||
const entities = await PostgresTestEntity.loader(vc1).loadManyByFieldEqualingAsync(
|
||||
'name',
|
||||
'hello',
|
||||
);
|
||||
expect(entities).toHaveLength(1);
|
||||
});
|
||||
|
||||
@@ -142,8 +132,7 @@ describe('postgres entity integration', () => {
|
||||
);
|
||||
|
||||
const firstEntity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'hello')
|
||||
.createAsync(),
|
||||
);
|
||||
@@ -156,12 +145,11 @@ describe('postgres entity integration', () => {
|
||||
await vc1.runInTransactionForDatabaseAdaptorFlavorAsync(
|
||||
'postgres',
|
||||
async (queryContext) => {
|
||||
const entity = await PostgresTestEntity.loader(vc1, queryContext)
|
||||
.enforcing()
|
||||
.loadByIDAsync(firstEntity.getID());
|
||||
const entity = await PostgresTestEntity.loader(vc1, queryContext).loadByIDAsync(
|
||||
firstEntity.getID(),
|
||||
);
|
||||
await setTimeout(delay);
|
||||
await PostgresTestEntity.updater(entity, queryContext)
|
||||
.enforcing()
|
||||
.setField('name', entity.getField('name') + ',' + newName)
|
||||
.updateAsync();
|
||||
},
|
||||
@@ -199,8 +187,7 @@ describe('postgres entity integration', () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
const entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('stringArray', ['hello', 'world'])
|
||||
.setField('jsonArrayField', ['hello', 'world'])
|
||||
.createAsync(),
|
||||
@@ -214,8 +201,7 @@ describe('postgres entity integration', () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
const entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('jsonObjectField', { hello: 'world' })
|
||||
.createAsync(),
|
||||
);
|
||||
@@ -227,14 +213,12 @@ describe('postgres entity integration', () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
const entity1 = await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('maybeJsonArrayField', ['hello', 'world'])
|
||||
.createAsync(),
|
||||
);
|
||||
const entity2 = await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('maybeJsonArrayField', { hello: 'world' })
|
||||
.createAsync(),
|
||||
);
|
||||
@@ -249,24 +233,21 @@ describe('postgres entity integration', () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
let entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('bigintField', '72057594037928038')
|
||||
.createAsync(),
|
||||
);
|
||||
expect(entity.getField('bigintField')).toEqual('72057594037928038');
|
||||
|
||||
entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.updater(entity)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.updaterWithAuthorizationResults(entity)
|
||||
.setField('bigintField', '10')
|
||||
.updateAsync(),
|
||||
);
|
||||
expect(entity.getField('bigintField')).toEqual('10');
|
||||
|
||||
entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.updater(entity)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.updaterWithAuthorizationResults(entity)
|
||||
.setField('bigintField', '-10')
|
||||
.updateAsync(),
|
||||
);
|
||||
@@ -274,13 +255,69 @@ describe('postgres entity integration', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('supports single field and composite field equality loading', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
const e1 = await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'hello')
|
||||
.setField('hasACat', false)
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'world')
|
||||
.setField('hasACat', false)
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'wat')
|
||||
.setField('hasACat', false)
|
||||
.setField('hasADog', false)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
const e1Loaded = await PostgresTestEntity.loader(vc1).loadByIDAsync(e1.getID());
|
||||
expect(e1Loaded).not.toBeNull();
|
||||
|
||||
const results = await PostgresTestEntity.loader(vc1).loadManyByFieldEqualingAsync(
|
||||
'hasACat',
|
||||
false,
|
||||
);
|
||||
expect(results).toHaveLength(3);
|
||||
|
||||
const compositeResults = await PostgresTestEntity.loader(
|
||||
vc1,
|
||||
).loadManyByCompositeFieldEqualingManyAsync(
|
||||
['hasACat', 'hasADog'],
|
||||
[
|
||||
{ hasACat: false, hasADog: true },
|
||||
{ hasACat: false, hasADog: false },
|
||||
],
|
||||
);
|
||||
expect(compositeResults.size).toBe(2);
|
||||
expect(compositeResults.get({ hasACat: false, hasADog: true })).toHaveLength(2);
|
||||
expect(compositeResults.get({ hasACat: false, hasADog: false })).toHaveLength(1);
|
||||
|
||||
const results2 = await PostgresTestEntity.loader(vc1).loadManyByFieldEqualingManyAsync(
|
||||
'hasADog',
|
||||
[true, false],
|
||||
);
|
||||
expect(results2.get(true)).toHaveLength(2);
|
||||
expect(results2.get(false)).toHaveLength(1);
|
||||
});
|
||||
|
||||
describe('conjunction field equality loading', () => {
|
||||
it('supports single fieldValue and multiple fieldValues', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'hello')
|
||||
.setField('hasACat', false)
|
||||
.setField('hasADog', true)
|
||||
@@ -288,8 +325,7 @@ describe('postgres entity integration', () => {
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'world')
|
||||
.setField('hasACat', false)
|
||||
.setField('hasADog', true)
|
||||
@@ -297,34 +333,29 @@ describe('postgres entity integration', () => {
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'wat')
|
||||
.setField('hasACat', false)
|
||||
.setField('hasADog', false)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
const results = await PostgresTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadManyByFieldEqualityConjunctionAsync([
|
||||
{
|
||||
fieldName: 'hasACat',
|
||||
fieldValue: false,
|
||||
},
|
||||
{
|
||||
fieldName: 'hasADog',
|
||||
fieldValue: true,
|
||||
},
|
||||
]);
|
||||
const results = await PostgresTestEntity.loader(vc1).loadManyByFieldEqualityConjunctionAsync([
|
||||
{
|
||||
fieldName: 'hasACat',
|
||||
fieldValue: false,
|
||||
},
|
||||
{
|
||||
fieldName: 'hasADog',
|
||||
fieldValue: true,
|
||||
},
|
||||
]);
|
||||
|
||||
expect(results).toHaveLength(2);
|
||||
|
||||
const results2 = await PostgresTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadManyByFieldEqualityConjunctionAsync([
|
||||
{ fieldName: 'hasADog', fieldValues: [true, false] },
|
||||
]);
|
||||
const results2 = await PostgresTestEntity.loader(vc1).loadManyByFieldEqualityConjunctionAsync(
|
||||
[{ fieldName: 'hasADog', fieldValues: [true, false] }],
|
||||
);
|
||||
expect(results2).toHaveLength(3);
|
||||
});
|
||||
|
||||
@@ -332,29 +363,20 @@ describe('postgres entity integration', () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
.setField('name', 'a')
|
||||
.createAsync(),
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1).setField('name', 'a').createAsync(),
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
.setField('name', 'b')
|
||||
.createAsync(),
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1).setField('name', 'b').createAsync(),
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
.setField('name', 'c')
|
||||
.createAsync(),
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1).setField('name', 'c').createAsync(),
|
||||
);
|
||||
|
||||
const results = await PostgresTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadManyByFieldEqualityConjunctionAsync([], {
|
||||
const results = await PostgresTestEntity.loader(vc1).loadManyByFieldEqualityConjunctionAsync(
|
||||
[],
|
||||
{
|
||||
limit: 2,
|
||||
offset: 1,
|
||||
orderBy: [
|
||||
@@ -363,7 +385,8 @@ describe('postgres entity integration', () => {
|
||||
order: OrderByOrdering.DESCENDING,
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
);
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results.map((e) => e.getField('name'))).toEqual(['b', 'a']);
|
||||
});
|
||||
@@ -371,56 +394,50 @@ describe('postgres entity integration', () => {
|
||||
it('supports null field values', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'a')
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'b')
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', null)
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', null)
|
||||
.setField('hasADog', false)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
const results = await PostgresTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadManyByFieldEqualityConjunctionAsync([{ fieldName: 'name', fieldValue: null }]);
|
||||
const results = await PostgresTestEntity.loader(vc1).loadManyByFieldEqualityConjunctionAsync([
|
||||
{ fieldName: 'name', fieldValue: null },
|
||||
]);
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results[0]!.getField('name')).toBeNull();
|
||||
|
||||
const results2 = await PostgresTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadManyByFieldEqualityConjunctionAsync(
|
||||
[
|
||||
{ fieldName: 'name', fieldValues: ['a', null] },
|
||||
{ fieldName: 'hasADog', fieldValue: true },
|
||||
const results2 = await PostgresTestEntity.loader(vc1).loadManyByFieldEqualityConjunctionAsync(
|
||||
[
|
||||
{ fieldName: 'name', fieldValues: ['a', null] },
|
||||
{ fieldName: 'hasADog', fieldValue: true },
|
||||
],
|
||||
{
|
||||
orderBy: [
|
||||
{
|
||||
fieldName: 'name',
|
||||
order: OrderByOrdering.DESCENDING,
|
||||
},
|
||||
],
|
||||
{
|
||||
orderBy: [
|
||||
{
|
||||
fieldName: 'name',
|
||||
order: OrderByOrdering.DESCENDING,
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
expect(results2).toHaveLength(2);
|
||||
expect(results2.map((e) => e.getField('name'))).toEqual([null, 'a']);
|
||||
});
|
||||
@@ -430,17 +447,17 @@ describe('postgres entity integration', () => {
|
||||
it('loads by raw where clause', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'hello')
|
||||
.setField('hasACat', false)
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
const results = await PostgresTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadManyByRawWhereClauseAsync('name = ?', ['hello']);
|
||||
const results = await PostgresTestEntity.loader(vc1).loadManyByRawWhereClauseAsync(
|
||||
'name = ?',
|
||||
['hello'],
|
||||
);
|
||||
|
||||
expect(results).toHaveLength(1);
|
||||
});
|
||||
@@ -448,8 +465,7 @@ describe('postgres entity integration', () => {
|
||||
it('throws with invalid where clause', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'hello')
|
||||
.setField('hasACat', false)
|
||||
.setField('hasADog', true)
|
||||
@@ -457,9 +473,9 @@ describe('postgres entity integration', () => {
|
||||
);
|
||||
|
||||
await expect(
|
||||
PostgresTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadManyByRawWhereClauseAsync('invalid_column = ?', ['hello']),
|
||||
PostgresTestEntity.loader(vc1).loadManyByRawWhereClauseAsync('invalid_column = ?', [
|
||||
'hello',
|
||||
]),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
@@ -467,32 +483,30 @@ describe('postgres entity integration', () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'a')
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'b')
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1)
|
||||
.withAuthorizationResults()
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'c')
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
const results = await PostgresTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadManyByRawWhereClauseAsync('has_a_dog = ?', [true], {
|
||||
const results = await PostgresTestEntity.loader(vc1).loadManyByRawWhereClauseAsync(
|
||||
'has_a_dog = ?',
|
||||
[true],
|
||||
{
|
||||
limit: 2,
|
||||
offset: 1,
|
||||
orderBy: [
|
||||
@@ -501,34 +515,37 @@ describe('postgres entity integration', () => {
|
||||
order: OrderByOrdering.ASCENDING,
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results.map((e) => e.getField('name'))).toEqual(['b', 'c']);
|
||||
|
||||
const resultsMultipleOrderBy = await PostgresTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadManyByRawWhereClauseAsync('has_a_dog = ?', [true], {
|
||||
orderBy: [
|
||||
{
|
||||
fieldName: 'hasADog',
|
||||
order: OrderByOrdering.ASCENDING,
|
||||
},
|
||||
{
|
||||
fieldName: 'name',
|
||||
order: OrderByOrdering.DESCENDING,
|
||||
},
|
||||
],
|
||||
});
|
||||
const resultsMultipleOrderBy = await PostgresTestEntity.loader(
|
||||
vc1,
|
||||
).loadManyByRawWhereClauseAsync('has_a_dog = ?', [true], {
|
||||
orderBy: [
|
||||
{
|
||||
fieldName: 'hasADog',
|
||||
order: OrderByOrdering.ASCENDING,
|
||||
},
|
||||
{
|
||||
fieldName: 'name',
|
||||
order: OrderByOrdering.DESCENDING,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(resultsMultipleOrderBy).toHaveLength(3);
|
||||
expect(resultsMultipleOrderBy.map((e) => e.getField('name'))).toEqual(['c', 'b', 'a']);
|
||||
|
||||
const resultsOrderByRaw = await PostgresTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadManyByRawWhereClauseAsync('has_a_dog = ?', [true], {
|
||||
const resultsOrderByRaw = await PostgresTestEntity.loader(vc1).loadManyByRawWhereClauseAsync(
|
||||
'has_a_dog = ?',
|
||||
[true],
|
||||
{
|
||||
orderByRaw: 'has_a_dog ASC, name DESC',
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
expect(resultsOrderByRaw).toHaveLength(3);
|
||||
expect(resultsOrderByRaw.map((e) => e.getField('name'))).toEqual(['c', 'b', 'a']);
|
||||
@@ -543,63 +560,38 @@ describe('postgres entity integration', () => {
|
||||
);
|
||||
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.creator(vc1)
|
||||
.enforcing()
|
||||
.setField('name', 'beforeCreate')
|
||||
.createAsync(),
|
||||
PostgresTriggerTestEntity.creator(vc1).setField('name', 'beforeCreate').createAsync(),
|
||||
).rejects.toThrowError('name cannot have value beforeCreate');
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'beforeCreate'),
|
||||
PostgresTriggerTestEntity.loader(vc1).loadByFieldEqualingAsync('name', 'beforeCreate'),
|
||||
).resolves.toBeNull();
|
||||
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.creator(vc1)
|
||||
.enforcing()
|
||||
.setField('name', 'afterCreate')
|
||||
.createAsync(),
|
||||
PostgresTriggerTestEntity.creator(vc1).setField('name', 'afterCreate').createAsync(),
|
||||
).rejects.toThrowError('name cannot have value afterCreate');
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'afterCreate'),
|
||||
PostgresTriggerTestEntity.loader(vc1).loadByFieldEqualingAsync('name', 'afterCreate'),
|
||||
).resolves.toBeNull();
|
||||
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.creator(vc1)
|
||||
.enforcing()
|
||||
.setField('name', 'beforeAll')
|
||||
.createAsync(),
|
||||
PostgresTriggerTestEntity.creator(vc1).setField('name', 'beforeAll').createAsync(),
|
||||
).rejects.toThrowError('name cannot have value beforeAll');
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'beforeAll'),
|
||||
PostgresTriggerTestEntity.loader(vc1).loadByFieldEqualingAsync('name', 'beforeAll'),
|
||||
).resolves.toBeNull();
|
||||
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.creator(vc1)
|
||||
.enforcing()
|
||||
.setField('name', 'afterAll')
|
||||
.createAsync(),
|
||||
PostgresTriggerTestEntity.creator(vc1).setField('name', 'afterAll').createAsync(),
|
||||
).rejects.toThrowError('name cannot have value afterAll');
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'afterAll'),
|
||||
PostgresTriggerTestEntity.loader(vc1).loadByFieldEqualingAsync('name', 'afterAll'),
|
||||
).resolves.toBeNull();
|
||||
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.creator(vc1)
|
||||
.enforcing()
|
||||
.setField('name', 'afterCommit')
|
||||
.createAsync(),
|
||||
PostgresTriggerTestEntity.creator(vc1).setField('name', 'afterCommit').createAsync(),
|
||||
).rejects.toThrowError('name cannot have value afterCommit');
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'afterCommit'),
|
||||
PostgresTriggerTestEntity.loader(vc1).loadByFieldEqualingAsync('name', 'afterCommit'),
|
||||
).resolves.not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -611,68 +603,42 @@ describe('postgres entity integration', () => {
|
||||
);
|
||||
|
||||
const entity = await PostgresTriggerTestEntity.creator(vc1)
|
||||
.enforcing()
|
||||
.setField('name', 'blah')
|
||||
.createAsync();
|
||||
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.updater(entity)
|
||||
.enforcing()
|
||||
.setField('name', 'beforeUpdate')
|
||||
.updateAsync(),
|
||||
PostgresTriggerTestEntity.updater(entity).setField('name', 'beforeUpdate').updateAsync(),
|
||||
).rejects.toThrowError('name cannot have value beforeUpdate');
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'beforeUpdate'),
|
||||
PostgresTriggerTestEntity.loader(vc1).loadByFieldEqualingAsync('name', 'beforeUpdate'),
|
||||
).resolves.toBeNull();
|
||||
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.updater(entity)
|
||||
.enforcing()
|
||||
.setField('name', 'afterUpdate')
|
||||
.updateAsync(),
|
||||
PostgresTriggerTestEntity.updater(entity).setField('name', 'afterUpdate').updateAsync(),
|
||||
).rejects.toThrowError('name cannot have value afterUpdate');
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'afterUpdate'),
|
||||
PostgresTriggerTestEntity.loader(vc1).loadByFieldEqualingAsync('name', 'afterUpdate'),
|
||||
).resolves.toBeNull();
|
||||
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.updater(entity)
|
||||
.enforcing()
|
||||
.setField('name', 'beforeAll')
|
||||
.updateAsync(),
|
||||
PostgresTriggerTestEntity.updater(entity).setField('name', 'beforeAll').updateAsync(),
|
||||
).rejects.toThrowError('name cannot have value beforeAll');
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'beforeAll'),
|
||||
PostgresTriggerTestEntity.loader(vc1).loadByFieldEqualingAsync('name', 'beforeAll'),
|
||||
).resolves.toBeNull();
|
||||
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.updater(entity)
|
||||
.enforcing()
|
||||
.setField('name', 'afterAll')
|
||||
.updateAsync(),
|
||||
PostgresTriggerTestEntity.updater(entity).setField('name', 'afterAll').updateAsync(),
|
||||
).rejects.toThrowError('name cannot have value afterAll');
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'afterAll'),
|
||||
PostgresTriggerTestEntity.loader(vc1).loadByFieldEqualingAsync('name', 'afterAll'),
|
||||
).resolves.toBeNull();
|
||||
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.updater(entity)
|
||||
.enforcing()
|
||||
.setField('name', 'afterCommit')
|
||||
.updateAsync(),
|
||||
PostgresTriggerTestEntity.updater(entity).setField('name', 'afterCommit').updateAsync(),
|
||||
).rejects.toThrowError('name cannot have value afterCommit');
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'afterCommit'),
|
||||
PostgresTriggerTestEntity.loader(vc1).loadByFieldEqualingAsync('name', 'afterCommit'),
|
||||
).resolves.not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -684,29 +650,23 @@ describe('postgres entity integration', () => {
|
||||
);
|
||||
|
||||
const entityBeforeDelete = await PostgresTriggerTestEntity.creator(vc1)
|
||||
.enforcing()
|
||||
.setField('name', 'beforeDelete')
|
||||
.createAsync();
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.deleter(entityBeforeDelete).enforcing().deleteAsync(),
|
||||
PostgresTriggerTestEntity.deleter(entityBeforeDelete).deleteAsync(),
|
||||
).rejects.toThrowError('name cannot have value beforeDelete');
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'beforeDelete'),
|
||||
PostgresTriggerTestEntity.loader(vc1).loadByFieldEqualingAsync('name', 'beforeDelete'),
|
||||
).resolves.not.toBeNull();
|
||||
|
||||
const entityAfterDelete = await PostgresTriggerTestEntity.creator(vc1)
|
||||
.enforcing()
|
||||
.setField('name', 'afterDelete')
|
||||
.createAsync();
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.deleter(entityAfterDelete).enforcing().deleteAsync(),
|
||||
PostgresTriggerTestEntity.deleter(entityAfterDelete).deleteAsync(),
|
||||
).rejects.toThrowError('name cannot have value afterDelete');
|
||||
await expect(
|
||||
PostgresTriggerTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'afterDelete'),
|
||||
PostgresTriggerTestEntity.loader(vc1).loadByFieldEqualingAsync('name', 'afterDelete'),
|
||||
).resolves.not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -719,14 +679,14 @@ describe('postgres entity integration', () => {
|
||||
|
||||
await expect(
|
||||
PostgresValidatorTestEntity.creator(vc1)
|
||||
.enforcing()
|
||||
.setField('name', 'beforeCreateAndBeforeUpdate')
|
||||
.createAsync(),
|
||||
).rejects.toThrowError('name cannot have value beforeCreateAndBeforeUpdate');
|
||||
await expect(
|
||||
PostgresValidatorTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'beforeCreateAndBeforeUpdate'),
|
||||
PostgresValidatorTestEntity.loader(vc1).loadByFieldEqualingAsync(
|
||||
'name',
|
||||
'beforeCreateAndBeforeUpdate',
|
||||
),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -737,20 +697,19 @@ describe('postgres entity integration', () => {
|
||||
);
|
||||
|
||||
const entity = await PostgresValidatorTestEntity.creator(vc1)
|
||||
.enforcing()
|
||||
.setField('name', 'blah')
|
||||
.createAsync();
|
||||
|
||||
await expect(
|
||||
PostgresValidatorTestEntity.updater(entity)
|
||||
.enforcing()
|
||||
.setField('name', 'beforeCreateAndBeforeUpdate')
|
||||
.updateAsync(),
|
||||
).rejects.toThrowError('name cannot have value beforeCreateAndBeforeUpdate');
|
||||
await expect(
|
||||
PostgresValidatorTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'beforeCreateAndBeforeUpdate'),
|
||||
PostgresValidatorTestEntity.loader(vc1).loadByFieldEqualingAsync(
|
||||
'name',
|
||||
'beforeCreateAndBeforeUpdate',
|
||||
),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -761,14 +720,14 @@ describe('postgres entity integration', () => {
|
||||
);
|
||||
|
||||
const entityToDelete = await PostgresValidatorTestEntity.creator(vc1)
|
||||
.enforcing()
|
||||
.setField('name', 'shouldBeDeleted')
|
||||
.createAsync();
|
||||
await PostgresValidatorTestEntity.deleter(entityToDelete).enforcing().deleteAsync();
|
||||
await PostgresValidatorTestEntity.deleter(entityToDelete).deleteAsync();
|
||||
await expect(
|
||||
PostgresValidatorTestEntity.loader(vc1)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', 'shouldBeDeleted'),
|
||||
PostgresValidatorTestEntity.loader(vc1).loadByFieldEqualingAsync(
|
||||
'name',
|
||||
'shouldBeDeleted',
|
||||
),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
+373
-28
@@ -1,10 +1,10 @@
|
||||
import { ViewerContext } from '@expo/entity';
|
||||
import { TransactionalDataLoaderMode, ViewerContext } from '@expo/entity';
|
||||
import { knex, Knex } from 'knex';
|
||||
import nullthrows from 'nullthrows';
|
||||
|
||||
import PostgresEntityQueryContextProvider from '../PostgresEntityQueryContextProvider';
|
||||
import PostgresUniqueTestEntity from '../testfixtures/PostgresUniqueTestEntity';
|
||||
import { createKnexIntegrationTestEntityCompanionProvider } from '../testfixtures/createKnexIntegrationTestEntityCompanionProvider';
|
||||
import PostgresUniqueTestEntity from '../__testfixtures__/PostgresUniqueTestEntity';
|
||||
import { createKnexIntegrationTestEntityCompanionProvider } from '../__testfixtures__/createKnexIntegrationTestEntityCompanionProvider';
|
||||
|
||||
describe(PostgresEntityQueryContextProvider, () => {
|
||||
let knexInstance: Knex;
|
||||
@@ -34,67 +34,412 @@ describe(PostgresEntityQueryContextProvider, () => {
|
||||
it('supports nested transactions', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
await PostgresUniqueTestEntity.creator(vc1)
|
||||
.enforcing()
|
||||
.setField('name', 'unique')
|
||||
.createAsync();
|
||||
await PostgresUniqueTestEntity.creator(vc1).setField('name', 'unique').createAsync();
|
||||
|
||||
const id = (
|
||||
await PostgresUniqueTestEntity.creator(vc1).enforcing().setField('name', 'wat').createAsync()
|
||||
await PostgresUniqueTestEntity.creator(vc1).setField('name', 'wat').createAsync()
|
||||
).getID();
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdaptorFlavorAsync('postgres', async (queryContext) => {
|
||||
const entity = await PostgresUniqueTestEntity.loader(vc1, queryContext)
|
||||
.enforcing()
|
||||
.loadByIDAsync(id);
|
||||
const entity = await PostgresUniqueTestEntity.loader(vc1, queryContext).loadByIDAsync(id);
|
||||
await PostgresUniqueTestEntity.updater(entity, queryContext)
|
||||
.enforcing()
|
||||
.setField('name', 'wat2')
|
||||
.updateAsync();
|
||||
|
||||
// ensure the outer transaction is not aborted due to postgres error in inner transaction,
|
||||
// in this case the error triggered is a unique constraint violation
|
||||
// in this case the error triggered is a unique constraint violation from a conflict with the first entity created above
|
||||
try {
|
||||
await queryContext.runInNestedTransactionAsync(async (innerQueryContext) => {
|
||||
const entity = await PostgresUniqueTestEntity.loader(vc1, innerQueryContext)
|
||||
.enforcing()
|
||||
.loadByIDAsync(id);
|
||||
const entity = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
innerQueryContext,
|
||||
).loadByIDAsync(id);
|
||||
await PostgresUniqueTestEntity.updater(entity, innerQueryContext)
|
||||
.enforcing()
|
||||
.setField('name', 'unique')
|
||||
.updateAsync();
|
||||
});
|
||||
} catch {}
|
||||
|
||||
const entity2 = await PostgresUniqueTestEntity.loader(vc1, queryContext)
|
||||
.enforcing()
|
||||
.loadByIDAsync(id);
|
||||
const entity2 = await PostgresUniqueTestEntity.loader(vc1, queryContext).loadByIDAsync(id);
|
||||
await PostgresUniqueTestEntity.updater(entity2, queryContext)
|
||||
.enforcing()
|
||||
.setField('name', 'wat3')
|
||||
.updateAsync();
|
||||
});
|
||||
|
||||
const entityLoaded = await PostgresUniqueTestEntity.loader(vc1).enforcing().loadByIDAsync(id);
|
||||
const entityLoaded = await PostgresUniqueTestEntity.loader(vc1).loadByIDAsync(id);
|
||||
expect(entityLoaded.getField('name')).toEqual('wat3');
|
||||
});
|
||||
|
||||
test('dataloader consistency with nested transactions', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
// put it in local dataloader
|
||||
const entity = await PostgresUniqueTestEntity.creator(vc1)
|
||||
.setField('name', 'who')
|
||||
.createAsync();
|
||||
const entityLoaded = await PostgresUniqueTestEntity.loader(vc1).loadByIDAsync(entity.getID());
|
||||
expect(entityLoaded.getField('name')).toEqual('who');
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdaptorFlavorAsync('postgres', async (queryContext) => {
|
||||
const entityLoadedOuter = await PostgresUniqueTestEntity.loader(vc1).loadByIDAsync(
|
||||
entity.getID(),
|
||||
);
|
||||
expect(entityLoadedOuter.getField('name')).toEqual('who');
|
||||
|
||||
await queryContext.runInNestedTransactionAsync(async (innerQueryContext) => {
|
||||
const entityLoadedInner = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
innerQueryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
const updatedEntity = await PostgresUniqueTestEntity.updater(
|
||||
entityLoadedInner,
|
||||
innerQueryContext,
|
||||
)
|
||||
.setField('name', 'wat')
|
||||
.updateAsync();
|
||||
expect(updatedEntity.getField('name')).toEqual('wat');
|
||||
});
|
||||
|
||||
const entityLoadedAfterNested = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
queryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
expect(entityLoadedAfterNested.getField('name')).toEqual('wat');
|
||||
});
|
||||
|
||||
const entityLoadedAfterTransaction = await PostgresUniqueTestEntity.loader(vc1).loadByIDAsync(
|
||||
entity.getID(),
|
||||
);
|
||||
expect(entityLoadedAfterTransaction.getField('name')).toEqual('wat');
|
||||
});
|
||||
|
||||
test('dataloader consistency with nested transactions that throw', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
// put it in local dataloader
|
||||
const entity = await PostgresUniqueTestEntity.creator(vc1)
|
||||
.setField('name', 'who')
|
||||
.createAsync();
|
||||
const entityLoaded = await PostgresUniqueTestEntity.loader(vc1).loadByIDAsync(entity.getID());
|
||||
expect(entityLoaded.getField('name')).toEqual('who');
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdaptorFlavorAsync('postgres', async (queryContext) => {
|
||||
const entityLoadedOuter = await PostgresUniqueTestEntity.loader(vc1).loadByIDAsync(
|
||||
entity.getID(),
|
||||
);
|
||||
expect(entityLoadedOuter.getField('name')).toEqual('who');
|
||||
|
||||
try {
|
||||
await queryContext.runInNestedTransactionAsync(async (innerQueryContext) => {
|
||||
const entityLoadedInner = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
innerQueryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
const updatedEntity = await PostgresUniqueTestEntity.updater(
|
||||
entityLoadedInner,
|
||||
innerQueryContext,
|
||||
)
|
||||
.setField('name', 'wat')
|
||||
.updateAsync();
|
||||
expect(updatedEntity.getField('name')).toEqual('wat');
|
||||
throw new Error('wat');
|
||||
});
|
||||
} catch {}
|
||||
|
||||
const entityLoadedAfterNested = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
queryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
expect(entityLoadedAfterNested.getField('name')).toEqual('who');
|
||||
});
|
||||
|
||||
const entityLoadedAfterTransaction = await PostgresUniqueTestEntity.loader(vc1).loadByIDAsync(
|
||||
entity.getID(),
|
||||
);
|
||||
expect(entityLoadedAfterTransaction.getField('name')).toEqual('who');
|
||||
});
|
||||
|
||||
test('dataloader consistency with concurrent loads outside of transaction', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
// put it in local dataloader
|
||||
const entity = await PostgresUniqueTestEntity.creator(vc1)
|
||||
.setField('name', 'who')
|
||||
.createAsync();
|
||||
const entityLoaded = await PostgresUniqueTestEntity.loader(vc1).loadByIDAsync(entity.getID());
|
||||
expect(entityLoaded.getField('name')).toEqual('who');
|
||||
|
||||
let openBarrier1: () => void;
|
||||
const barrier1 = new Promise<void>((resolve) => {
|
||||
openBarrier1 = resolve;
|
||||
});
|
||||
|
||||
let openBarrier2: () => void;
|
||||
const barrier2 = new Promise<void>((resolve) => {
|
||||
openBarrier2 = resolve;
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
vc1.runInTransactionForDatabaseAdaptorFlavorAsync('postgres', async (queryContext) => {
|
||||
const entityLoadedOuter = await PostgresUniqueTestEntity.loader(vc1).loadByIDAsync(
|
||||
entity.getID(),
|
||||
);
|
||||
expect(entityLoadedOuter.getField('name')).toEqual('who');
|
||||
|
||||
await queryContext.runInNestedTransactionAsync(async (innerQueryContext) => {
|
||||
const entityLoadedInner = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
innerQueryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
const updatedEntity = await PostgresUniqueTestEntity.updater(
|
||||
entityLoadedInner,
|
||||
innerQueryContext,
|
||||
)
|
||||
.setField('name', 'wat')
|
||||
.updateAsync();
|
||||
expect(updatedEntity.getField('name')).toEqual('wat');
|
||||
const entityLoadedAfterUpdate = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
innerQueryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
expect(entityLoadedAfterUpdate.getField('name')).toEqual('wat');
|
||||
});
|
||||
openBarrier1();
|
||||
await barrier2;
|
||||
}),
|
||||
(async () => {
|
||||
await barrier1;
|
||||
|
||||
const entityLoadedOutsideOfTransactionsBeforeNestedCommit =
|
||||
await PostgresUniqueTestEntity.loader(vc1).loadByIDAsync(entity.getID());
|
||||
expect(entityLoadedOutsideOfTransactionsBeforeNestedCommit.getField('name')).toEqual('who');
|
||||
openBarrier2!();
|
||||
})(),
|
||||
]);
|
||||
|
||||
const entityLoadedAfterTransaction = await PostgresUniqueTestEntity.loader(vc1).loadByIDAsync(
|
||||
entity.getID(),
|
||||
);
|
||||
expect(entityLoadedAfterTransaction.getField('name')).toEqual('wat');
|
||||
});
|
||||
|
||||
test('consistent behavior with and without transactional dataloader for concurrent loads outside of nested transaction', async () => {
|
||||
// Subtransactions are not supported in postgres. See #194 for more info.
|
||||
// Instead, savepoints and rollbacks are used to simulate subtransactions, which results in non-isolated read semantics.
|
||||
//
|
||||
// This test tests the same behavior exists whether there is a dataloader or not in transactions, thus indicating that
|
||||
// the dataloader invalidation is not the issue.
|
||||
|
||||
const runTest = async (
|
||||
transactionalDataLoaderMode: TransactionalDataLoaderMode,
|
||||
): Promise<void> => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await vc1.runInTransactionForDatabaseAdaptorFlavorAsync(
|
||||
'postgres',
|
||||
async (outerQueryContext) => {
|
||||
// put it in local dataloader
|
||||
const entity = await PostgresUniqueTestEntity.creator(vc1, outerQueryContext)
|
||||
.setField('name', 'who')
|
||||
.createAsync();
|
||||
const entityLoaded = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
outerQueryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
if (entityLoaded.getField('name') !== 'who') {
|
||||
throw new Error('entity loaded wrong value');
|
||||
}
|
||||
|
||||
let openBarrier1: () => void;
|
||||
const barrier1 = new Promise<void>((resolve) => {
|
||||
openBarrier1 = resolve;
|
||||
});
|
||||
|
||||
let openBarrier2: () => void;
|
||||
const barrier2 = new Promise<void>((resolve) => {
|
||||
openBarrier2 = resolve;
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
outerQueryContext.runInNestedTransactionAsync(async (innerQueryContext) => {
|
||||
const entityLoadedInner = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
innerQueryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
const updatedEntity = await PostgresUniqueTestEntity.updater(
|
||||
entityLoadedInner,
|
||||
innerQueryContext,
|
||||
)
|
||||
.setField('name', 'wat')
|
||||
.updateAsync();
|
||||
if (updatedEntity.getField('name') !== 'wat') {
|
||||
throw new Error('entity updated wrong value');
|
||||
}
|
||||
|
||||
const entityLoadedAfterUpdate = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
innerQueryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
if (entityLoadedAfterUpdate.getField('name') !== 'wat') {
|
||||
throw new Error('entity loaded wrong value after update');
|
||||
}
|
||||
openBarrier1();
|
||||
await barrier2;
|
||||
}),
|
||||
(async () => {
|
||||
await barrier1;
|
||||
|
||||
// if postgres supported nested transactions, this would read isolated from the nested transaction above
|
||||
// but since it doesn't, this will read the updated value.
|
||||
const entityLoadedInOuterTransactionBeforeNestedCommit =
|
||||
await PostgresUniqueTestEntity.loader(vc1, outerQueryContext).loadByIDAsync(
|
||||
entity.getID(),
|
||||
);
|
||||
if (entityLoadedInOuterTransactionBeforeNestedCommit.getField('name') !== 'who') {
|
||||
throw new Error('outer transaction read wrong value');
|
||||
}
|
||||
|
||||
openBarrier2!();
|
||||
})(),
|
||||
]);
|
||||
|
||||
const entityLoadedAfterTransaction = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
outerQueryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
if (entityLoadedAfterTransaction.getField('name') !== 'wat') {
|
||||
throw new Error('entity loaded wrong value after transaction');
|
||||
}
|
||||
},
|
||||
{ transactionalDataLoaderMode },
|
||||
);
|
||||
};
|
||||
|
||||
await expect(runTest(TransactionalDataLoaderMode.DISABLED)).rejects.toThrow(
|
||||
'outer transaction read wrong value',
|
||||
);
|
||||
await expect(runTest(TransactionalDataLoaderMode.ENABLED)).rejects.toThrow(
|
||||
'outer transaction read wrong value',
|
||||
);
|
||||
await expect(runTest(TransactionalDataLoaderMode.ENABLED_BATCH_ONLY)).rejects.toThrow(
|
||||
'outer transaction read wrong value',
|
||||
);
|
||||
});
|
||||
|
||||
test('consistent behavior with and without transactional dataloader for concurrent mutations outside of nested transaction that reads', async () => {
|
||||
// this test has a similar issue to the one above: absence of real nested transactions in postgres
|
||||
// this should have the same behavior no matter if there is a dataloader or not in transactions
|
||||
|
||||
const runTest = async (
|
||||
transactionalDataLoaderMode: TransactionalDataLoaderMode,
|
||||
): Promise<void> => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await vc1.runInTransactionForDatabaseAdaptorFlavorAsync(
|
||||
'postgres',
|
||||
async (outerQueryContext) => {
|
||||
// put it in local dataloader
|
||||
const entity = await PostgresUniqueTestEntity.creator(vc1, outerQueryContext)
|
||||
.setField('name', 'who')
|
||||
.createAsync();
|
||||
const entityLoaded = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
outerQueryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
if (entityLoaded.getField('name') !== 'who') {
|
||||
throw new Error('entity loaded wrong value');
|
||||
}
|
||||
|
||||
let openBarrier1: () => void;
|
||||
const barrier1 = new Promise<void>((resolve) => {
|
||||
openBarrier1 = resolve;
|
||||
});
|
||||
|
||||
let openBarrier2: () => void;
|
||||
const barrier2 = new Promise<void>((resolve) => {
|
||||
openBarrier2 = resolve;
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
(async () => {
|
||||
await barrier1;
|
||||
|
||||
const entityLoadedOuterAgain = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
outerQueryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
const updatedEntity = await PostgresUniqueTestEntity.updater(
|
||||
entityLoadedOuterAgain,
|
||||
outerQueryContext,
|
||||
)
|
||||
.setField('name', 'wat')
|
||||
.updateAsync();
|
||||
if (updatedEntity.getField('name') !== 'wat') {
|
||||
throw new Error('entity updated wrong value');
|
||||
}
|
||||
|
||||
openBarrier2!();
|
||||
})(),
|
||||
|
||||
outerQueryContext.runInNestedTransactionAsync(async (innerQueryContext) => {
|
||||
const entityLoadedInner = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
innerQueryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
if (entityLoadedInner.getField('name') !== 'who') {
|
||||
throw new Error('entity loaded inner wrong value 1');
|
||||
}
|
||||
|
||||
openBarrier1();
|
||||
await barrier2;
|
||||
|
||||
const entityLoadedInnerAgain = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
innerQueryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
if (entityLoadedInnerAgain.getField('name') !== 'who') {
|
||||
throw new Error('entity loaded inner wrong value 2');
|
||||
}
|
||||
}),
|
||||
]);
|
||||
|
||||
const entityLoadedAfterTransaction = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
outerQueryContext,
|
||||
).loadByIDAsync(entity.getID());
|
||||
if (entityLoadedAfterTransaction.getField('name') !== 'wat') {
|
||||
throw new Error('entity loaded wrong value after transaction');
|
||||
}
|
||||
},
|
||||
{ transactionalDataLoaderMode },
|
||||
);
|
||||
};
|
||||
|
||||
await expect(runTest(TransactionalDataLoaderMode.DISABLED)).rejects.toThrow(
|
||||
'entity loaded inner wrong value 2',
|
||||
);
|
||||
await expect(runTest(TransactionalDataLoaderMode.ENABLED)).rejects.toThrow(
|
||||
'entity loaded inner wrong value 2',
|
||||
);
|
||||
await expect(runTest(TransactionalDataLoaderMode.ENABLED_BATCH_ONLY)).rejects.toThrow(
|
||||
'entity loaded inner wrong value 2',
|
||||
);
|
||||
});
|
||||
|
||||
it('supports multi-nested transactions', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
const id = (
|
||||
await PostgresUniqueTestEntity.creator(vc1).enforcing().setField('name', 'wat').createAsync()
|
||||
await PostgresUniqueTestEntity.creator(vc1).setField('name', 'wat').createAsync()
|
||||
).getID();
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdaptorFlavorAsync('postgres', async (queryContext) => {
|
||||
await queryContext.runInNestedTransactionAsync(async (innerQueryContext) => {
|
||||
await innerQueryContext.runInNestedTransactionAsync(async (innerQueryContex2) => {
|
||||
await innerQueryContex2.runInNestedTransactionAsync(async (innerQueryContex3) => {
|
||||
const entity = await PostgresUniqueTestEntity.loader(vc1, innerQueryContex3)
|
||||
.enforcing()
|
||||
.loadByIDAsync(id);
|
||||
const entity = await PostgresUniqueTestEntity.loader(
|
||||
vc1,
|
||||
innerQueryContex3,
|
||||
).loadByIDAsync(id);
|
||||
await PostgresUniqueTestEntity.updater(entity, innerQueryContex3)
|
||||
.enforcing()
|
||||
.setField('name', 'wat3')
|
||||
.updateAsync();
|
||||
});
|
||||
@@ -102,7 +447,7 @@ describe(PostgresEntityQueryContextProvider, () => {
|
||||
});
|
||||
});
|
||||
|
||||
const entityLoaded = await PostgresUniqueTestEntity.loader(vc1).enforcing().loadByIDAsync(id);
|
||||
const entityLoaded = await PostgresUniqueTestEntity.loader(vc1).loadByIDAsync(id);
|
||||
expect(entityLoaded.getField('name')).toEqual('wat3');
|
||||
});
|
||||
});
|
||||
+13
-18
@@ -3,8 +3,8 @@ import { enforceAsyncResult } from '@expo/results';
|
||||
import { knex, Knex } from 'knex';
|
||||
import nullthrows from 'nullthrows';
|
||||
|
||||
import InvalidTestEntity from '../testfixtures/InvalidTestEntity';
|
||||
import { createKnexIntegrationTestEntityCompanionProvider } from '../testfixtures/createKnexIntegrationTestEntityCompanionProvider';
|
||||
import InvalidTestEntity from '../__testfixtures__/InvalidTestEntity';
|
||||
import { createKnexIntegrationTestEntityCompanionProvider } from '../__testfixtures__/createKnexIntegrationTestEntityCompanionProvider';
|
||||
|
||||
describe('postgres entity integration', () => {
|
||||
let knexInstance: Knex;
|
||||
@@ -35,60 +35,55 @@ describe('postgres entity integration', () => {
|
||||
it('throws after deletion of multiple rows or no rows', async () => {
|
||||
const vc = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entity1 = await enforceAsyncResult(
|
||||
InvalidTestEntity.creator(vc)
|
||||
.withAuthorizationResults()
|
||||
InvalidTestEntity.creatorWithAuthorizationResults(vc)
|
||||
.setField('id', 1)
|
||||
.setField('name', 'hello')
|
||||
.createAsync(),
|
||||
);
|
||||
await enforceAsyncResult(
|
||||
InvalidTestEntity.creator(vc)
|
||||
.withAuthorizationResults()
|
||||
InvalidTestEntity.creatorWithAuthorizationResults(vc)
|
||||
.setField('id', 1)
|
||||
.setField('name', 'world')
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await expect(
|
||||
InvalidTestEntity.deleter(entity1).enforcing().deleteAsync(),
|
||||
).rejects.toThrowError('Excessive deletions from database adapter delete');
|
||||
await expect(InvalidTestEntity.deleter(entity1).deleteAsync()).rejects.toThrowError(
|
||||
'Excessive deletions from database adapter delete',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws after update of multiple rows', async () => {
|
||||
const vc = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entity1 = await enforceAsyncResult(
|
||||
InvalidTestEntity.creator(vc)
|
||||
.withAuthorizationResults()
|
||||
InvalidTestEntity.creatorWithAuthorizationResults(vc)
|
||||
.setField('id', 1)
|
||||
.setField('name', 'hello')
|
||||
.createAsync(),
|
||||
);
|
||||
await enforceAsyncResult(
|
||||
InvalidTestEntity.creator(vc)
|
||||
.withAuthorizationResults()
|
||||
InvalidTestEntity.creatorWithAuthorizationResults(vc)
|
||||
.setField('id', 1)
|
||||
.setField('name', 'world')
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await expect(
|
||||
InvalidTestEntity.updater(entity1).enforcing().setField('name', 'blah').updateAsync(),
|
||||
InvalidTestEntity.updater(entity1).setField('name', 'blah').updateAsync(),
|
||||
).rejects.toThrowError('Excessive results from database adapter update');
|
||||
});
|
||||
|
||||
it('throws after update of no rows', async () => {
|
||||
const vc = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entity1 = await enforceAsyncResult(
|
||||
InvalidTestEntity.creator(vc)
|
||||
.withAuthorizationResults()
|
||||
InvalidTestEntity.creatorWithAuthorizationResults(vc)
|
||||
.setField('id', 1)
|
||||
.setField('name', 'hello')
|
||||
.createAsync(),
|
||||
);
|
||||
await InvalidTestEntity.deleter(entity1).enforcing().deleteAsync();
|
||||
await InvalidTestEntity.deleter(entity1).deleteAsync();
|
||||
|
||||
await expect(
|
||||
InvalidTestEntity.updater(entity1).enforcing().setField('name', 'blah').updateAsync(),
|
||||
InvalidTestEntity.updater(entity1).setField('name', 'blah').updateAsync(),
|
||||
).rejects.toThrowError('Empty results from database adapter update');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,8 +11,8 @@ import {
|
||||
import { knex, Knex } from 'knex';
|
||||
import nullthrows from 'nullthrows';
|
||||
|
||||
import ErrorsTestEntity from '../testfixtures/ErrorsTestEntity';
|
||||
import { createKnexIntegrationTestEntityCompanionProvider } from '../testfixtures/createKnexIntegrationTestEntityCompanionProvider';
|
||||
import ErrorsTestEntity from '../__testfixtures__/ErrorsTestEntity';
|
||||
import { createKnexIntegrationTestEntityCompanionProvider } from '../__testfixtures__/createKnexIntegrationTestEntityCompanionProvider';
|
||||
|
||||
describe('postgres errors', () => {
|
||||
let knexInstance: Knex;
|
||||
@@ -42,7 +42,6 @@ describe('postgres errors', () => {
|
||||
it('throws EntityDatabaseAdapterTransientError on Knex timeout', async () => {
|
||||
const vc = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await ErrorsTestEntity.creator(vc)
|
||||
.enforcing()
|
||||
.setField('id', 1)
|
||||
.setField('fieldNonNull', 'hello')
|
||||
.createAsync();
|
||||
@@ -61,7 +60,7 @@ describe('postgres errors', () => {
|
||||
const vc2 = new ViewerContext(
|
||||
createKnexIntegrationTestEntityCompanionProvider(shortTimeoutKnexInstance),
|
||||
);
|
||||
await expect(ErrorsTestEntity.loader(vc2).enforcing().loadByIDAsync(1)).rejects.toThrow(
|
||||
await expect(ErrorsTestEntity.loader(vc2).loadByIDAsync(1)).rejects.toThrow(
|
||||
EntityDatabaseAdapterTransientError,
|
||||
);
|
||||
await shortTimeoutKnexInstance.destroy();
|
||||
@@ -71,7 +70,6 @@ describe('postgres errors', () => {
|
||||
const vc = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await expect(
|
||||
ErrorsTestEntity.creator(vc)
|
||||
.enforcing()
|
||||
.setField('id', 1)
|
||||
.setField('fieldNonNull', null as any)
|
||||
.createAsync(),
|
||||
@@ -82,7 +80,6 @@ describe('postgres errors', () => {
|
||||
const vc = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await expect(
|
||||
ErrorsTestEntity.creator(vc)
|
||||
.enforcing()
|
||||
.setField('id', 1)
|
||||
.setField('fieldNonNull', 'hello')
|
||||
.setField('fieldForeignKey', 2)
|
||||
@@ -94,14 +91,12 @@ describe('postgres errors', () => {
|
||||
const vc = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
await ErrorsTestEntity.creator(vc)
|
||||
.enforcing()
|
||||
.setField('id', 1)
|
||||
.setField('fieldNonNull', 'hello')
|
||||
.createAsync();
|
||||
|
||||
await expect(
|
||||
ErrorsTestEntity.creator(vc)
|
||||
.enforcing()
|
||||
.setField('id', 1)
|
||||
.setField('fieldNonNull', 'hello')
|
||||
.createAsync(),
|
||||
@@ -111,7 +106,6 @@ describe('postgres errors', () => {
|
||||
it('throws EntityDatabaseAdapterUniqueConstraintError when unique constraint is violated', async () => {
|
||||
const vc = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await ErrorsTestEntity.creator(vc)
|
||||
.enforcing()
|
||||
.setField('id', 2)
|
||||
.setField('fieldNonNull', 'hello')
|
||||
.setField('fieldUnique', 'hello')
|
||||
@@ -119,7 +113,6 @@ describe('postgres errors', () => {
|
||||
|
||||
await expect(
|
||||
ErrorsTestEntity.creator(vc)
|
||||
.enforcing()
|
||||
.setField('id', 1)
|
||||
.setField('fieldNonNull', 'hello')
|
||||
.setField('fieldUnique', 'hello')
|
||||
@@ -131,7 +124,6 @@ describe('postgres errors', () => {
|
||||
const vc = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await expect(
|
||||
ErrorsTestEntity.creator(vc)
|
||||
.enforcing()
|
||||
.setField('id', 1)
|
||||
.setField('fieldNonNull', 'hello')
|
||||
.setField('checkLessThan5', 2)
|
||||
@@ -140,7 +132,6 @@ describe('postgres errors', () => {
|
||||
|
||||
await expect(
|
||||
ErrorsTestEntity.creator(vc)
|
||||
.enforcing()
|
||||
.setField('id', 2)
|
||||
.setField('fieldNonNull', 'hello')
|
||||
.setField('checkLessThan5', 10)
|
||||
@@ -152,7 +143,6 @@ describe('postgres errors', () => {
|
||||
const vc = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await expect(
|
||||
ErrorsTestEntity.creator(vc)
|
||||
.enforcing()
|
||||
.setField('id', 1)
|
||||
.setField('fieldNonNull', 'hello')
|
||||
.setField('fieldExclusion', 'what')
|
||||
@@ -161,7 +151,6 @@ describe('postgres errors', () => {
|
||||
|
||||
await expect(
|
||||
ErrorsTestEntity.creator(vc)
|
||||
.enforcing()
|
||||
.setField('id', 2)
|
||||
.setField('fieldNonNull', 'hello')
|
||||
.setField('fieldExclusion', 'what')
|
||||
@@ -173,7 +162,6 @@ describe('postgres errors', () => {
|
||||
const vc = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await expect(
|
||||
ErrorsTestEntity.creator(vc)
|
||||
.enforcing()
|
||||
.setField('id', 1)
|
||||
.setField('fieldNonNull', 'hello')
|
||||
.setField('nonExistentColumn', 'what')
|
||||
|
||||
+9
-12
@@ -22,14 +22,10 @@ type ErrorsTestEntityFields = {
|
||||
|
||||
const foreignTableName = 'foreign_table';
|
||||
|
||||
export default class ErrorsTestEntity extends Entity<
|
||||
ErrorsTestEntityFields,
|
||||
number,
|
||||
ViewerContext
|
||||
> {
|
||||
export default class ErrorsTestEntity extends Entity<ErrorsTestEntityFields, 'id', ViewerContext> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
ErrorsTestEntityFields,
|
||||
number,
|
||||
'id',
|
||||
ViewerContext,
|
||||
ErrorsTestEntity,
|
||||
ErrorsTestEntityPrivacyPolicy
|
||||
@@ -105,14 +101,14 @@ export default class ErrorsTestEntity extends Entity<
|
||||
|
||||
class ErrorsTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
ErrorsTestEntityFields,
|
||||
number,
|
||||
'id',
|
||||
ViewerContext,
|
||||
ErrorsTestEntity
|
||||
> {
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
ErrorsTestEntityFields,
|
||||
number,
|
||||
'id',
|
||||
ViewerContext,
|
||||
ErrorsTestEntity
|
||||
>(),
|
||||
@@ -120,7 +116,7 @@ class ErrorsTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
ErrorsTestEntityFields,
|
||||
number,
|
||||
'id',
|
||||
ViewerContext,
|
||||
ErrorsTestEntity
|
||||
>(),
|
||||
@@ -128,7 +124,7 @@ class ErrorsTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
ErrorsTestEntityFields,
|
||||
number,
|
||||
'id',
|
||||
ViewerContext,
|
||||
ErrorsTestEntity
|
||||
>(),
|
||||
@@ -136,19 +132,20 @@ class ErrorsTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
ErrorsTestEntityFields,
|
||||
number,
|
||||
'id',
|
||||
ViewerContext,
|
||||
ErrorsTestEntity
|
||||
>(),
|
||||
];
|
||||
}
|
||||
|
||||
export const ErrorsTestEntityConfiguration = new EntityConfiguration<ErrorsTestEntityFields>({
|
||||
export const ErrorsTestEntityConfiguration = new EntityConfiguration<ErrorsTestEntityFields, 'id'>({
|
||||
idField: 'id',
|
||||
tableName: 'postgres_test_entities',
|
||||
schema: {
|
||||
id: new IntField({
|
||||
columnName: 'id',
|
||||
cache: false,
|
||||
}),
|
||||
fieldNonNull: new StringField({
|
||||
columnName: 'field_non_null',
|
||||
+12
-8
@@ -17,12 +17,12 @@ type InvalidTestEntityFields = {
|
||||
|
||||
export default class InvalidTestEntity extends Entity<
|
||||
InvalidTestEntityFields,
|
||||
number,
|
||||
'id',
|
||||
ViewerContext
|
||||
> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
InvalidTestEntityFields,
|
||||
number,
|
||||
'id',
|
||||
ViewerContext,
|
||||
InvalidTestEntity,
|
||||
InvalidTestEntityPrivacyPolicy
|
||||
@@ -57,14 +57,14 @@ export default class InvalidTestEntity extends Entity<
|
||||
|
||||
class InvalidTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
InvalidTestEntityFields,
|
||||
number,
|
||||
'id',
|
||||
ViewerContext,
|
||||
InvalidTestEntity
|
||||
> {
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
InvalidTestEntityFields,
|
||||
number,
|
||||
'id',
|
||||
ViewerContext,
|
||||
InvalidTestEntity
|
||||
>(),
|
||||
@@ -72,7 +72,7 @@ class InvalidTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
InvalidTestEntityFields,
|
||||
number,
|
||||
'id',
|
||||
ViewerContext,
|
||||
InvalidTestEntity
|
||||
>(),
|
||||
@@ -80,7 +80,7 @@ class InvalidTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
InvalidTestEntityFields,
|
||||
number,
|
||||
'id',
|
||||
ViewerContext,
|
||||
InvalidTestEntity
|
||||
>(),
|
||||
@@ -88,19 +88,23 @@ class InvalidTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
InvalidTestEntityFields,
|
||||
number,
|
||||
'id',
|
||||
ViewerContext,
|
||||
InvalidTestEntity
|
||||
>(),
|
||||
];
|
||||
}
|
||||
|
||||
export const invalidTestEntityConfiguration = new EntityConfiguration<InvalidTestEntityFields>({
|
||||
export const invalidTestEntityConfiguration = new EntityConfiguration<
|
||||
InvalidTestEntityFields,
|
||||
'id'
|
||||
>({
|
||||
idField: 'id',
|
||||
tableName: 'postgres_test_entities',
|
||||
schema: {
|
||||
id: new IntField({
|
||||
columnName: 'id',
|
||||
cache: false,
|
||||
}),
|
||||
name: new StringField({
|
||||
columnName: 'name',
|
||||
+13
-9
@@ -2,7 +2,6 @@ import {
|
||||
AlwaysAllowPrivacyPolicyRule,
|
||||
EntityPrivacyPolicy,
|
||||
ViewerContext,
|
||||
UUIDField,
|
||||
StringField,
|
||||
BooleanField,
|
||||
StringArrayField,
|
||||
@@ -11,6 +10,7 @@ import {
|
||||
EntityConfiguration,
|
||||
EntityCompanionDefinition,
|
||||
Entity,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
import { Knex } from 'knex';
|
||||
|
||||
@@ -33,12 +33,12 @@ type PostgresTestEntityFields = {
|
||||
|
||||
export default class PostgresTestEntity extends Entity<
|
||||
PostgresTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext
|
||||
> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
PostgresTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTestEntity,
|
||||
PostgresTestEntityPrivacyPolicy
|
||||
@@ -81,14 +81,14 @@ export default class PostgresTestEntity extends Entity<
|
||||
|
||||
class PostgresTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
PostgresTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTestEntity
|
||||
> {
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTestEntity
|
||||
>(),
|
||||
@@ -96,7 +96,7 @@ class PostgresTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTestEntity
|
||||
>(),
|
||||
@@ -104,7 +104,7 @@ class PostgresTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTestEntity
|
||||
>(),
|
||||
@@ -112,14 +112,17 @@ class PostgresTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTestEntity
|
||||
>(),
|
||||
];
|
||||
}
|
||||
|
||||
export const postgresTestEntityConfiguration = new EntityConfiguration<PostgresTestEntityFields>({
|
||||
export const postgresTestEntityConfiguration = new EntityConfiguration<
|
||||
PostgresTestEntityFields,
|
||||
'id'
|
||||
>({
|
||||
idField: 'id',
|
||||
tableName: 'postgres_test_entities',
|
||||
schema: {
|
||||
@@ -157,4 +160,5 @@ export const postgresTestEntityConfiguration = new EntityConfiguration<PostgresT
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
compositeFieldDefinitions: [{ compositeField: ['hasACat', 'hasADog'], cache: false }],
|
||||
});
|
||||
+29
-27
@@ -2,7 +2,6 @@ import {
|
||||
AlwaysAllowPrivacyPolicyRule,
|
||||
EntityPrivacyPolicy,
|
||||
ViewerContext,
|
||||
UUIDField,
|
||||
StringField,
|
||||
EntityConfiguration,
|
||||
EntityCompanionDefinition,
|
||||
@@ -11,6 +10,7 @@ import {
|
||||
EntityQueryContext,
|
||||
EntityNonTransactionalMutationTrigger,
|
||||
EntityTriggerMutationInfo,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
import { Knex } from 'knex';
|
||||
|
||||
@@ -21,12 +21,12 @@ type PostgresTriggerTestEntityFields = {
|
||||
|
||||
export default class PostgresTriggerTestEntity extends Entity<
|
||||
PostgresTriggerTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext
|
||||
> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
PostgresTriggerTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTriggerTestEntity,
|
||||
PostgresTriggerTestEntityPrivacyPolicy
|
||||
@@ -72,14 +72,14 @@ export default class PostgresTriggerTestEntity extends Entity<
|
||||
|
||||
class PostgresTriggerTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
PostgresTriggerTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTriggerTestEntity
|
||||
> {
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresTriggerTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTriggerTestEntity
|
||||
>(),
|
||||
@@ -87,7 +87,7 @@ class PostgresTriggerTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresTriggerTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTriggerTestEntity
|
||||
>(),
|
||||
@@ -95,7 +95,7 @@ class PostgresTriggerTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresTriggerTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTriggerTestEntity
|
||||
>(),
|
||||
@@ -103,7 +103,7 @@ class PostgresTriggerTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresTriggerTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTriggerTestEntity
|
||||
>(),
|
||||
@@ -112,7 +112,7 @@ class PostgresTriggerTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
|
||||
class ThrowConditionallyTrigger extends EntityMutationTrigger<
|
||||
PostgresTriggerTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTriggerTestEntity
|
||||
> {
|
||||
@@ -129,7 +129,7 @@ class ThrowConditionallyTrigger extends EntityMutationTrigger<
|
||||
entity: PostgresTriggerTestEntity,
|
||||
_mutationInfo: EntityTriggerMutationInfo<
|
||||
PostgresTriggerTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTriggerTestEntity
|
||||
>,
|
||||
@@ -142,7 +142,7 @@ class ThrowConditionallyTrigger extends EntityMutationTrigger<
|
||||
|
||||
class ThrowConditionallyNonTransactionalTrigger extends EntityNonTransactionalMutationTrigger<
|
||||
PostgresTriggerTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresTriggerTestEntity
|
||||
> {
|
||||
@@ -163,19 +163,21 @@ class ThrowConditionallyNonTransactionalTrigger extends EntityNonTransactionalMu
|
||||
}
|
||||
}
|
||||
|
||||
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: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
});
|
||||
export const postgresTestEntityConfiguration = new EntityConfiguration<
|
||||
PostgresTriggerTestEntityFields,
|
||||
'id'
|
||||
>({
|
||||
idField: 'id',
|
||||
tableName: 'postgres_test_entities',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
name: new StringField({
|
||||
columnName: 'name',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
});
|
||||
+26
-24
@@ -2,11 +2,11 @@ import {
|
||||
AlwaysAllowPrivacyPolicyRule,
|
||||
EntityPrivacyPolicy,
|
||||
ViewerContext,
|
||||
UUIDField,
|
||||
StringField,
|
||||
EntityConfiguration,
|
||||
EntityCompanionDefinition,
|
||||
Entity,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
import { Knex } from 'knex';
|
||||
|
||||
@@ -17,12 +17,12 @@ type PostgresUniqueTestEntityFields = {
|
||||
|
||||
export default class PostgresUniqueTestEntity extends Entity<
|
||||
PostgresUniqueTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext
|
||||
> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
PostgresUniqueTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresUniqueTestEntity,
|
||||
PostgresUniqueTestEntityPrivacyPolicy
|
||||
@@ -57,14 +57,14 @@ export default class PostgresUniqueTestEntity extends Entity<
|
||||
|
||||
class PostgresUniqueTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
PostgresUniqueTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresUniqueTestEntity
|
||||
> {
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresUniqueTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresUniqueTestEntity
|
||||
>(),
|
||||
@@ -72,7 +72,7 @@ class PostgresUniqueTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresUniqueTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresUniqueTestEntity
|
||||
>(),
|
||||
@@ -80,7 +80,7 @@ class PostgresUniqueTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresUniqueTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresUniqueTestEntity
|
||||
>(),
|
||||
@@ -88,26 +88,28 @@ class PostgresUniqueTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresUniqueTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresUniqueTestEntity
|
||||
>(),
|
||||
];
|
||||
}
|
||||
|
||||
export const postgresTestEntityConfiguration =
|
||||
new EntityConfiguration<PostgresUniqueTestEntityFields>({
|
||||
idField: 'id',
|
||||
tableName: 'postgres_test_entities',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
name: new StringField({
|
||||
columnName: 'name',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
});
|
||||
export const postgresTestEntityConfiguration = new EntityConfiguration<
|
||||
PostgresUniqueTestEntityFields,
|
||||
'id'
|
||||
>({
|
||||
idField: 'id',
|
||||
tableName: 'postgres_test_entities',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
name: new StringField({
|
||||
columnName: 'name',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
});
|
||||
+28
-26
@@ -2,7 +2,6 @@ import {
|
||||
AlwaysAllowPrivacyPolicyRule,
|
||||
EntityPrivacyPolicy,
|
||||
ViewerContext,
|
||||
UUIDField,
|
||||
StringField,
|
||||
EntityConfiguration,
|
||||
EntityCompanionDefinition,
|
||||
@@ -10,6 +9,7 @@ import {
|
||||
EntityMutationTrigger,
|
||||
EntityQueryContext,
|
||||
EntityValidatorMutationInfo,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
import { Knex } from 'knex';
|
||||
|
||||
@@ -20,12 +20,12 @@ type PostgresValidatorTestEntityFields = {
|
||||
|
||||
export default class PostgresValidatorTestEntity extends Entity<
|
||||
PostgresValidatorTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext
|
||||
> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
PostgresValidatorTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresValidatorTestEntity,
|
||||
PostgresValidatorTestEntityPrivacyPolicy
|
||||
@@ -61,14 +61,14 @@ export default class PostgresValidatorTestEntity extends Entity<
|
||||
|
||||
class PostgresValidatorTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
PostgresValidatorTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresValidatorTestEntity
|
||||
> {
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresValidatorTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresValidatorTestEntity
|
||||
>(),
|
||||
@@ -76,7 +76,7 @@ class PostgresValidatorTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresValidatorTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresValidatorTestEntity
|
||||
>(),
|
||||
@@ -84,7 +84,7 @@ class PostgresValidatorTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresValidatorTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresValidatorTestEntity
|
||||
>(),
|
||||
@@ -92,7 +92,7 @@ class PostgresValidatorTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresValidatorTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresValidatorTestEntity
|
||||
>(),
|
||||
@@ -101,7 +101,7 @@ class PostgresValidatorTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
|
||||
class ThrowConditionallyTrigger extends EntityMutationTrigger<
|
||||
PostgresValidatorTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresValidatorTestEntity
|
||||
> {
|
||||
@@ -118,7 +118,7 @@ class ThrowConditionallyTrigger extends EntityMutationTrigger<
|
||||
entity: PostgresValidatorTestEntity,
|
||||
_mutationInfo: EntityValidatorMutationInfo<
|
||||
PostgresValidatorTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
PostgresValidatorTestEntity
|
||||
>,
|
||||
@@ -129,19 +129,21 @@ class ThrowConditionallyTrigger extends EntityMutationTrigger<
|
||||
}
|
||||
}
|
||||
|
||||
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: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
});
|
||||
export const postgresTestEntityConfiguration = new EntityConfiguration<
|
||||
PostgresValidatorTestEntityFields,
|
||||
'id'
|
||||
>({
|
||||
idField: 'id',
|
||||
tableName: 'postgres_test_entities',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
name: new StringField({
|
||||
columnName: 'name',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
});
|
||||
+1
-1
@@ -2,8 +2,8 @@ import {
|
||||
NoOpEntityMetricsAdapter,
|
||||
IEntityMetricsAdapter,
|
||||
EntityCompanionProvider,
|
||||
InMemoryFullCacheStubCacheAdapterProvider,
|
||||
} from '@expo/entity';
|
||||
import { InMemoryFullCacheStubCacheAdapterProvider } from '@expo/entity-testing-utils';
|
||||
import { Knex } from 'knex';
|
||||
|
||||
import PostgresEntityDatabaseAdapterProvider from '../PostgresEntityDatabaseAdapterProvider';
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describeFieldTestCase } from '@expo/entity';
|
||||
import { describeFieldTestCase } from '@expo/entity-testing-utils';
|
||||
|
||||
import { BigIntField, JSONArrayField, MaybeJSONArrayField } from '../EntityFields';
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.build.json",
|
||||
"include": ["src"],
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "build",
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -3,6 +3,51 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.44.0](https://github.com/expo/entity/compare/v0.43.0...v0.44.0) (2025-05-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-example
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.43.0](https://github.com/expo/entity/compare/v0.42.0...v0.43.0) (2025-04-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-example
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.42.0](https://github.com/expo/entity/compare/v0.41.0...v0.42.0) (2025-04-10)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add @expo/entity-testing-utils package ([#280](https://github.com/expo/entity/issues/280)) ([485894a](https://github.com/expo/entity/commit/485894af16e233d533a9480285bbda56812cbe0b))
|
||||
* add composite field loading and caching ([#272](https://github.com/expo/entity/issues/272)) ([f0aa0da](https://github.com/expo/entity/commit/f0aa0dafebdb56418cbd22dda437233d850db3e7))
|
||||
* change entity id field generic to field name and derive type where necessary ([#278](https://github.com/expo/entity/issues/278)) ([b7e524c](https://github.com/expo/entity/commit/b7e524c41892797608d0b884410b8d520a80a9ef))
|
||||
* convert batched/cached loader interface to holder pattern ([#271](https://github.com/expo/entity/issues/271)) ([06b3cb7](https://github.com/expo/entity/commit/06b3cb7f8076ef9e5b83cdf154da159801bd14cc)), closes [#201](https://github.com/expo/entity/issues/201)
|
||||
* enforce explicit id field cache property ([#276](https://github.com/expo/entity/issues/276)) ([1da5cc0](https://github.com/expo/entity/commit/1da5cc01e1affc3b3338a0ab2050504b5853ac6f))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.41.0](https://github.com/expo/entity/compare/v0.40.0...v0.41.0) (2025-03-07)
|
||||
|
||||
|
||||
* feat!: Default all loaders and mutators to enforcing (#256) ([a976e76](https://github.com/expo/entity/commit/a976e765098bca27049585e43a3bed5c71b9ac6b)), closes [#256](https://github.com/expo/entity/issues/256)
|
||||
|
||||
|
||||
### BREAKING CHANGES
|
||||
|
||||
* Default all loaders and mutators to enforcing
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.40.0](https://github.com/expo/entity/compare/v0.39.0...v0.40.0) (2025-02-27)
|
||||
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
{
|
||||
"name": "@expo/entity-example",
|
||||
"private": true,
|
||||
"version": "0.40.0",
|
||||
"version": "0.44.0",
|
||||
"description": "An example integration of the @expo/entity framework",
|
||||
"scripts": {
|
||||
"tsc": "tsc",
|
||||
"build": "tsc -b tsconfig.build.json",
|
||||
"clean": "rm -rf build coverage coverage-integration",
|
||||
"lint": "eslint src",
|
||||
"lint-fix": "eslint src --fix",
|
||||
@@ -25,6 +26,7 @@
|
||||
"@apollo/server": "^4.7.3",
|
||||
"@as-integrations/koa": "^1.1.1",
|
||||
"@expo/entity": "workspace:^",
|
||||
"@expo/entity-testing-utils": "workspace:^",
|
||||
"@koa/cors": "^4.0.0",
|
||||
"@koa/router": "^12.0.0",
|
||||
"graphql": "^16.6.0",
|
||||
@@ -32,22 +34,22 @@
|
||||
"koa-bodyparser": "^4.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/koa": "^2.13.6",
|
||||
"@types/koa-bodyparser": "^4.3.10",
|
||||
"@types/koa__cors": "^4.0.0",
|
||||
"@types/koa__router": "^12.0.0",
|
||||
"@types/node": "^20.14.1",
|
||||
"@types/supertest": "^2.0.10",
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-config-universe": "^14.0.0",
|
||||
"eslint-plugin-tsdoc": "^0.3.0",
|
||||
"eslint": "^9.26.0",
|
||||
"eslint-config-universe": "^15.0.3",
|
||||
"eslint-plugin-tsdoc": "^0.4.0",
|
||||
"jest": "^29.7.0",
|
||||
"prettier": "^3.3.3",
|
||||
"prettier": "^3.5.3",
|
||||
"supertest": "^4.0.2",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-jest": "^29.3.2",
|
||||
"ts-mockito": "^2.6.1",
|
||||
"ts-node-dev": "^1.0.0-pre.60",
|
||||
"typescript": "^5.7.3"
|
||||
"typescript": "^5.8.3"
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createUnitTestEntityCompanionProvider } from '@expo/entity';
|
||||
import { createUnitTestEntityCompanionProvider } from '@expo/entity-testing-utils';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import NoteEntity from '../entities/NoteEntity';
|
||||
@@ -10,16 +10,16 @@ describe(NoteEntity, () => {
|
||||
const userId = uuidv4();
|
||||
const viewerContext = new UserViewerContext(companionProvider, userId);
|
||||
|
||||
const createdEntityResult = await NoteEntity.creator(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
const createdEntityResult = await NoteEntity.creatorWithAuthorizationResults(viewerContext)
|
||||
.setField('userID', userId)
|
||||
.setField('body', 'image')
|
||||
.setField('title', 'page')
|
||||
.createAsync();
|
||||
expect(createdEntityResult.ok).toBe(true);
|
||||
|
||||
const createdEntityResultImpersonate = await NoteEntity.creator(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
const createdEntityResultImpersonate = await NoteEntity.creatorWithAuthorizationResults(
|
||||
viewerContext,
|
||||
)
|
||||
.setField('userID', uuidv4()) // a different user
|
||||
.setField('body', 'image')
|
||||
.setField('title', 'page')
|
||||
|
||||
@@ -15,9 +15,9 @@ import { v4 as uuidv4 } from 'uuid';
|
||||
const dbObjects: Readonly<{ [key: string]: any }>[] = [];
|
||||
|
||||
export class InMemoryDatabaseAdapterProvider implements IEntityDatabaseAdapterProvider {
|
||||
getDatabaseAdapter<TFields extends Record<string, any>>(
|
||||
entityConfiguration: EntityConfiguration<TFields>,
|
||||
): EntityDatabaseAdapter<TFields> {
|
||||
getDatabaseAdapter<TFields extends Record<string, any>, TIDField extends keyof TFields>(
|
||||
entityConfiguration: EntityConfiguration<TFields, TIDField>,
|
||||
): EntityDatabaseAdapter<TFields, TIDField> {
|
||||
return new InMemoryDatabaseAdapter(entityConfiguration);
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,10 @@ export class InMemoryDatabaseAdapterProvider implements IEntityDatabaseAdapterPr
|
||||
* In-memory database adapter for entity for the purposes of this example. Normally `@expo/entity-database-adapter-knex`
|
||||
* or another production adapter would be used. Very similar to StubDatabaseAdapter but shared in a way more akin to a normal database.
|
||||
*/
|
||||
class InMemoryDatabaseAdapter<T extends Record<string, any>> extends EntityDatabaseAdapter<T> {
|
||||
class InMemoryDatabaseAdapter<
|
||||
TFields extends Record<string, any>,
|
||||
TIDField extends keyof TFields,
|
||||
> extends EntityDatabaseAdapter<TFields, TIDField> {
|
||||
protected getFieldTransformerMap(): FieldTransformerMap {
|
||||
return new Map();
|
||||
}
|
||||
@@ -34,16 +37,19 @@ class InMemoryDatabaseAdapter<T extends Record<string, any>> extends EntityDatab
|
||||
protected async fetchManyWhereInternalAsync(
|
||||
_queryInterface: any,
|
||||
_tableName: string,
|
||||
tableField: string,
|
||||
tableValues: readonly any[],
|
||||
tableColumns: readonly string[],
|
||||
tableTuples: (readonly any[])[],
|
||||
): Promise<object[]> {
|
||||
return tableValues.reduce((acc, fieldValue) => {
|
||||
const results = tableTuples.reduce((acc, tableTuple) => {
|
||||
return acc.concat(
|
||||
dbObjects.filter((obj) => {
|
||||
return obj[tableField] === fieldValue;
|
||||
return tableColumns.every((tableColumn, index) => {
|
||||
return obj[tableColumn] === tableTuple[index];
|
||||
});
|
||||
}),
|
||||
);
|
||||
}, []);
|
||||
return [...results];
|
||||
}
|
||||
|
||||
private static compareByOrderBys(
|
||||
@@ -128,7 +134,7 @@ class InMemoryDatabaseAdapter<T extends Record<string, any>> extends EntityDatab
|
||||
_tableName: string,
|
||||
object: object,
|
||||
): Promise<object[]> {
|
||||
const configurationPrivate = this['entityConfiguration'] as EntityConfiguration<T>;
|
||||
const configurationPrivate = this['entityConfiguration'];
|
||||
const idField = getDatabaseFieldForEntityField(
|
||||
configurationPrivate,
|
||||
configurationPrivate.idField,
|
||||
|
||||
@@ -2,8 +2,8 @@ import {
|
||||
IEntityMetricsAdapter,
|
||||
NoOpEntityMetricsAdapter,
|
||||
EntityCompanionProvider,
|
||||
InMemoryFullCacheStubCacheAdapterProvider,
|
||||
} from '@expo/entity';
|
||||
import { InMemoryFullCacheStubCacheAdapterProvider } from '@expo/entity-testing-utils';
|
||||
|
||||
import { InMemoryDatabaseAdapterProvider } from './adapters/InMemoryDatabaseAdapter';
|
||||
import InMemoryQueryContextProvider from './adapters/InMemoryQueryContextProvider';
|
||||
|
||||
@@ -23,11 +23,11 @@ import { ExampleViewerContext } from '../viewerContexts';
|
||||
* Otherwise, it defers to the next rule in the policy.
|
||||
*/
|
||||
export default class AllowIfUserOwnerPrivacyRule<
|
||||
TFields extends object,
|
||||
TID extends NonNullable<TFields[TSelectedFields]>,
|
||||
TEntity extends ReadonlyEntity<TFields, TID, ExampleViewerContext>,
|
||||
TFields extends Record<string, any>,
|
||||
TIDField extends keyof NonNullable<Pick<TFields, TSelectedFields>>,
|
||||
TEntity extends ReadonlyEntity<TFields, TIDField, ExampleViewerContext>,
|
||||
TSelectedFields extends keyof TFields = keyof TFields,
|
||||
> extends PrivacyPolicyRule<TFields, TID, ExampleViewerContext, TEntity> {
|
||||
> extends PrivacyPolicyRule<TFields, TIDField, ExampleViewerContext, TEntity> {
|
||||
constructor(private readonly entityOwnerField: keyof TFields) {
|
||||
super();
|
||||
}
|
||||
@@ -37,7 +37,7 @@ export default class AllowIfUserOwnerPrivacyRule<
|
||||
_queryContext: EntityQueryContext,
|
||||
_evaluationContext: EntityPrivacyPolicyEvaluationContext<
|
||||
TFields,
|
||||
TID,
|
||||
TIDField,
|
||||
ExampleViewerContext,
|
||||
TEntity,
|
||||
TSelectedFields
|
||||
|
||||
@@ -2,8 +2,8 @@ import {
|
||||
Entity,
|
||||
EntityCompanionDefinition,
|
||||
EntityConfiguration,
|
||||
UUIDField,
|
||||
StringField,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
|
||||
import NotePrivacyPolicy from './NotePrivacyPolicy';
|
||||
@@ -19,7 +19,7 @@ export interface NoteFields {
|
||||
/**
|
||||
* A simple entity representing a "notes" table/collection. Each note has an owner, title, and body.
|
||||
*/
|
||||
export default class NoteEntity extends Entity<NoteFields, string, ExampleViewerContext> {
|
||||
export default class NoteEntity extends Entity<NoteFields, 'id', ExampleViewerContext> {
|
||||
/**
|
||||
* The companion provides configuration instructions to the Entity framework for this type
|
||||
* of entity. In some languages, this would be representable as "abstract" static members
|
||||
@@ -27,19 +27,20 @@ export default class NoteEntity extends Entity<NoteFields, string, ExampleViewer
|
||||
*/
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
NoteFields,
|
||||
string,
|
||||
'id',
|
||||
ExampleViewerContext,
|
||||
NoteEntity,
|
||||
NotePrivacyPolicy
|
||||
> {
|
||||
return {
|
||||
entityClass: NoteEntity,
|
||||
entityConfiguration: new EntityConfiguration<NoteFields>({
|
||||
entityConfiguration: new EntityConfiguration<NoteFields, 'id'>({
|
||||
idField: 'id',
|
||||
tableName: 'notes',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
userID: new UUIDField({
|
||||
columnName: 'user_id',
|
||||
|
||||
@@ -9,20 +9,20 @@ import { ExampleViewerContext } from '../viewerContexts';
|
||||
*/
|
||||
export default class NotePrivacyPolicy extends EntityPrivacyPolicy<
|
||||
NoteFields,
|
||||
string,
|
||||
'id',
|
||||
ExampleViewerContext,
|
||||
NoteEntity
|
||||
> {
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<NoteFields, string, ExampleViewerContext, NoteEntity>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<NoteFields, 'id', ExampleViewerContext, NoteEntity>(),
|
||||
];
|
||||
protected override readonly createRules = [
|
||||
new AllowIfUserOwnerPrivacyRule<NoteFields, string, NoteEntity>('userID'),
|
||||
new AllowIfUserOwnerPrivacyRule<NoteFields, 'id', NoteEntity>('userID'),
|
||||
];
|
||||
protected override readonly updateRules = [
|
||||
new AllowIfUserOwnerPrivacyRule<NoteFields, string, NoteEntity>('userID'),
|
||||
new AllowIfUserOwnerPrivacyRule<NoteFields, 'id', NoteEntity>('userID'),
|
||||
];
|
||||
protected override readonly deleteRules = [
|
||||
new AllowIfUserOwnerPrivacyRule<NoteFields, string, NoteEntity>('userID'),
|
||||
new AllowIfUserOwnerPrivacyRule<NoteFields, 'id', NoteEntity>('userID'),
|
||||
];
|
||||
}
|
||||
@@ -19,9 +19,10 @@ router.get('/', async (ctx) => {
|
||||
const viewerContext = ctx.state.viewerContext;
|
||||
let notes: readonly NoteEntity[] = [];
|
||||
if (viewerContext.isUserViewerContext()) {
|
||||
notes = await NoteEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadManyByFieldEqualingAsync('userID', viewerContext.userID);
|
||||
notes = await NoteEntity.loader(viewerContext).loadManyByFieldEqualingAsync(
|
||||
'userID',
|
||||
viewerContext.userID,
|
||||
);
|
||||
}
|
||||
ctx.body = {
|
||||
notes: notes.map((note) => note.getAllFields()),
|
||||
@@ -30,9 +31,9 @@ router.get('/', async (ctx) => {
|
||||
|
||||
router.get('/:id', async (ctx) => {
|
||||
const viewerContext = ctx.state.viewerContext;
|
||||
const noteResult = await NoteEntity.loader(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
.loadByIDAsync(ctx.params['id']!);
|
||||
const noteResult = await NoteEntity.loaderWithAuthorizationResults(viewerContext).loadByIDAsync(
|
||||
ctx.params['id']!,
|
||||
);
|
||||
if (!noteResult.ok) {
|
||||
ctx.throw(403, noteResult.reason);
|
||||
return;
|
||||
@@ -55,8 +56,7 @@ router.post('/', async (ctx) => {
|
||||
|
||||
const { title, body } = ctx.request.body as any;
|
||||
|
||||
const createResult = await NoteEntity.creator(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
const createResult = await NoteEntity.creatorWithAuthorizationResults(viewerContext)
|
||||
.setField('userID', viewerContext.userID)
|
||||
.setField('title', title)
|
||||
.setField('body', body)
|
||||
@@ -75,16 +75,15 @@ router.put('/:id', async (ctx) => {
|
||||
const viewerContext = ctx.state.viewerContext;
|
||||
const { title, body } = ctx.request.body as any;
|
||||
|
||||
const noteLoadResult = await NoteEntity.loader(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
.loadByIDAsync(ctx.params['id']!);
|
||||
const noteLoadResult = await NoteEntity.loaderWithAuthorizationResults(
|
||||
viewerContext,
|
||||
).loadByIDAsync(ctx.params['id']!);
|
||||
if (!noteLoadResult.ok) {
|
||||
ctx.throw(403, noteLoadResult.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
const noteUpdateResult = await NoteEntity.updater(noteLoadResult.value)
|
||||
.withAuthorizationResults()
|
||||
const noteUpdateResult = await NoteEntity.updaterWithAuthorizationResults(noteLoadResult.value)
|
||||
.setField('title', title)
|
||||
.setField('body', body)
|
||||
.updateAsync();
|
||||
@@ -101,17 +100,17 @@ router.put('/:id', async (ctx) => {
|
||||
router.delete('/:id', async (ctx) => {
|
||||
const viewerContext = ctx.state.viewerContext;
|
||||
|
||||
const noteLoadResult = await NoteEntity.loader(viewerContext)
|
||||
.withAuthorizationResults()
|
||||
.loadByIDAsync(ctx.params['id']!);
|
||||
const noteLoadResult = await NoteEntity.loaderWithAuthorizationResults(
|
||||
viewerContext,
|
||||
).loadByIDAsync(ctx.params['id']!);
|
||||
if (!noteLoadResult.ok) {
|
||||
ctx.throw(403, noteLoadResult.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
const noteDeleteResult = await NoteEntity.deleter(noteLoadResult.value)
|
||||
.withAuthorizationResults()
|
||||
.deleteAsync();
|
||||
const noteDeleteResult = await NoteEntity.deleterWithAuthorizationResults(
|
||||
noteLoadResult.value,
|
||||
).deleteAsync();
|
||||
if (!noteDeleteResult.ok) {
|
||||
ctx.throw(403, noteDeleteResult.reason);
|
||||
return;
|
||||
|
||||
@@ -46,16 +46,14 @@ export const resolvers: IResolvers<any, GraphqlContext> = {
|
||||
return viewerContext.userID;
|
||||
},
|
||||
async noteByID(_root, args, { viewerContext }) {
|
||||
return await NoteEntity.loader(viewerContext).enforcing().loadByIDAsync(args.id);
|
||||
return await NoteEntity.loader(viewerContext).loadByIDAsync(args.id);
|
||||
},
|
||||
} as IObjectTypeResolver<any, GraphqlContext>,
|
||||
|
||||
User: {
|
||||
id: (root) => root,
|
||||
async notes(root, _args, { viewerContext }) {
|
||||
return await NoteEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadManyByFieldEqualingAsync('userID', root);
|
||||
return await NoteEntity.loader(viewerContext).loadManyByFieldEqualingAsync('userID', root);
|
||||
},
|
||||
} as IObjectTypeResolver<string, GraphqlContext>,
|
||||
|
||||
@@ -73,27 +71,21 @@ export const resolvers: IResolvers<any, GraphqlContext> = {
|
||||
}
|
||||
|
||||
return await NoteEntity.creator(viewerContext)
|
||||
.enforcing()
|
||||
.setField('userID', viewerContext.userID)
|
||||
.setField('title', args.note.title)
|
||||
.setField('body', args.note.body)
|
||||
.createAsync();
|
||||
},
|
||||
async updateNote(_root, args, { viewerContext }) {
|
||||
const existingNote = await NoteEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadByIDAsync(args.id);
|
||||
const existingNote = await NoteEntity.loader(viewerContext).loadByIDAsync(args.id);
|
||||
return await NoteEntity.updater(existingNote)
|
||||
.enforcing()
|
||||
.setField('title', args.note.title)
|
||||
.setField('body', args.note.body)
|
||||
.updateAsync();
|
||||
},
|
||||
async deleteNote(_root, args, { viewerContext }) {
|
||||
const existingNote = await NoteEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadByIDAsync(args.id);
|
||||
await NoteEntity.deleter(existingNote).enforcing().deleteAsync();
|
||||
const existingNote = await NoteEntity.loader(viewerContext).loadByIDAsync(args.id);
|
||||
await NoteEntity.deleter(existingNote).deleteAsync();
|
||||
return existingNote;
|
||||
},
|
||||
} as IObjectTypeResolver<any, GraphqlContext>,
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.build.json",
|
||||
"include": ["src"],
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -3,6 +3,52 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.44.0](https://github.com/expo/entity/compare/v0.43.0...v0.44.0) (2025-05-29)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add transaction-scoped dataloaders ([#284](https://github.com/expo/entity/issues/284)) ([e054a0d](https://github.com/expo/entity/commit/e054a0d74b3a39158ca7d73d05f59d3633113400)), closes [#98](https://github.com/expo/entity/issues/98) [#194](https://github.com/expo/entity/issues/194)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.43.0](https://github.com/expo/entity/compare/v0.42.0...v0.43.0) (2025-04-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-full-integration-tests
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.42.0](https://github.com/expo/entity/compare/v0.41.0...v0.42.0) (2025-04-10)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add @expo/entity-testing-utils package ([#280](https://github.com/expo/entity/issues/280)) ([485894a](https://github.com/expo/entity/commit/485894af16e233d533a9480285bbda56812cbe0b))
|
||||
* change entity id field generic to field name and derive type where necessary ([#278](https://github.com/expo/entity/issues/278)) ([b7e524c](https://github.com/expo/entity/commit/b7e524c41892797608d0b884410b8d520a80a9ef))
|
||||
* invalidate n+/-1 cacheKeyVersion for entities for push safety ([#275](https://github.com/expo/entity/issues/275)) ([d9c1852](https://github.com/expo/entity/commit/d9c1852706f98f0761ff24ddd244e4ed2beca580))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.41.0](https://github.com/expo/entity/compare/v0.40.0...v0.41.0) (2025-03-07)
|
||||
|
||||
|
||||
* feat!: Default all loaders and mutators to enforcing (#256) ([a976e76](https://github.com/expo/entity/commit/a976e765098bca27049585e43a3bed5c71b9ac6b)), closes [#256](https://github.com/expo/entity/issues/256)
|
||||
|
||||
|
||||
### BREAKING CHANGES
|
||||
|
||||
* Default all loaders and mutators to enforcing
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.40.0](https://github.com/expo/entity/compare/v0.39.0...v0.40.0) (2025-02-27)
|
||||
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
{
|
||||
"name": "@expo/entity-full-integration-tests",
|
||||
"private": true,
|
||||
"version": "0.40.0",
|
||||
"version": "0.44.0",
|
||||
"description": "Full redis and knex integration tests for the entity framework",
|
||||
"scripts": {
|
||||
"tsc": "tsc",
|
||||
"build": "tsc -b tsconfig.build.json",
|
||||
"clean": "rm -rf build coverage coverage-integration",
|
||||
"lint": "eslint src",
|
||||
"lint-fix": "eslint src --fix",
|
||||
@@ -26,15 +27,15 @@
|
||||
"@expo/entity-database-adapter-knex": "workspace:^"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^20.14.1",
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-config-universe": "^14.0.0",
|
||||
"eslint-plugin-tsdoc": "^0.3.0",
|
||||
"eslint": "^9.26.0",
|
||||
"eslint-config-universe": "^15.0.3",
|
||||
"eslint-plugin-tsdoc": "^0.4.0",
|
||||
"jest": "^29.7.0",
|
||||
"prettier": "^3.3.3",
|
||||
"ts-jest": "^29.2.5",
|
||||
"prettier": "^3.5.3",
|
||||
"ts-jest": "^29.3.2",
|
||||
"ts-mockito": "^2.6.1",
|
||||
"typescript": "^5.7.3"
|
||||
"typescript": "^5.8.3"
|
||||
}
|
||||
}
|
||||
+24
-25
@@ -5,16 +5,19 @@ import {
|
||||
Entity,
|
||||
EntityCompanionDefinition,
|
||||
EntityConfiguration,
|
||||
UUIDField,
|
||||
StringField,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
import { GenericRedisCacheContext } from '@expo/entity-cache-adapter-redis';
|
||||
import {
|
||||
GenericRedisCacheContext,
|
||||
RedisCacheInvalidationStrategy,
|
||||
} from '@expo/entity-cache-adapter-redis';
|
||||
import Redis from 'ioredis';
|
||||
import { knex, Knex } from 'knex';
|
||||
import nullthrows from 'nullthrows';
|
||||
import { URL } from 'url';
|
||||
|
||||
import { createFullIntegrationTestEntityCompanionProvider } from '../testfixtures/createFullIntegrationTestEntityCompanionProvider';
|
||||
import { createFullIntegrationTestEntityCompanionProvider } from '../__testfixtures__/createFullIntegrationTestEntityCompanionProvider';
|
||||
|
||||
interface TestFields {
|
||||
id: string;
|
||||
@@ -24,28 +27,28 @@ interface TestFields {
|
||||
|
||||
class TestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
TestFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
TestEntity
|
||||
> {
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, string, ViewerContext, TestEntity>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, 'id', ViewerContext, TestEntity>(),
|
||||
];
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, string, ViewerContext, TestEntity>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, 'id', ViewerContext, TestEntity>(),
|
||||
];
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, string, ViewerContext, TestEntity>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, 'id', ViewerContext, TestEntity>(),
|
||||
];
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, string, ViewerContext, TestEntity>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, 'id', ViewerContext, TestEntity>(),
|
||||
];
|
||||
}
|
||||
|
||||
class TestEntity extends Entity<TestFields, string, ViewerContext> {
|
||||
class TestEntity extends Entity<TestFields, 'id', ViewerContext> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
TestFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
TestEntity,
|
||||
TestEntityPrivacyPolicy
|
||||
@@ -58,7 +61,7 @@ class TestEntity extends Entity<TestFields, string, ViewerContext> {
|
||||
}
|
||||
}
|
||||
|
||||
const testEntityConfiguration = new EntityConfiguration<TestFields>({
|
||||
const testEntityConfiguration = new EntityConfiguration<TestFields, 'id'>({
|
||||
idField: 'id',
|
||||
tableName: 'testentities',
|
||||
schema: {
|
||||
@@ -81,7 +84,7 @@ const testEntityConfiguration = new EntityConfiguration<TestFields>({
|
||||
async function createOrTruncatePostgresTablesAsync(knex: Knex): Promise<void> {
|
||||
await knex.schema.createTable('testentities', (table) => {
|
||||
table.uuid('id').defaultTo(knex.raw('gen_random_uuid()')).primary();
|
||||
table.string('other_string').notNullable();
|
||||
table.string('other_string').notNullable().unique();
|
||||
table.string('third_string').notNullable();
|
||||
});
|
||||
await knex.into('testentities').truncate();
|
||||
@@ -121,6 +124,7 @@ describe('Entity cache inconsistency', () => {
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -141,16 +145,13 @@ describe('Entity cache inconsistency', () => {
|
||||
);
|
||||
|
||||
const entity1 = await TestEntity.creator(viewerContext)
|
||||
.enforcing()
|
||||
.setField('other_string', 'hello')
|
||||
.setField('third_string', 'initial')
|
||||
.createAsync();
|
||||
|
||||
// put entities in cache and dataloader
|
||||
await TestEntity.loader(viewerContext).enforcing().loadByIDAsync(entity1.getID());
|
||||
await TestEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('other_string', 'hello');
|
||||
await TestEntity.loader(viewerContext).loadByIDAsync(entity1.getID());
|
||||
await TestEntity.loader(viewerContext).loadByFieldEqualingAsync('other_string', 'hello');
|
||||
|
||||
let openBarrier1: () => void;
|
||||
const barrier1 = new Promise<void>((resolve) => {
|
||||
@@ -173,7 +174,7 @@ describe('Entity cache inconsistency', () => {
|
||||
const viewerContextInternal = new ViewerContext(
|
||||
createFullIntegrationTestEntityCompanionProvider(knexInstance, genericRedisCacheContext),
|
||||
);
|
||||
await TestEntity.loader(viewerContextInternal).enforcing().loadByIDAsync(entity1.getID());
|
||||
await TestEntity.loader(viewerContextInternal).loadByIDAsync(entity1.getID());
|
||||
|
||||
openBarrier2!();
|
||||
})(),
|
||||
@@ -181,7 +182,6 @@ describe('Entity cache inconsistency', () => {
|
||||
'postgres',
|
||||
async (queryContext) => {
|
||||
await TestEntity.updater(entity1, queryContext)
|
||||
.enforcing()
|
||||
.setField('third_string', 'updated')
|
||||
.updateAsync();
|
||||
|
||||
@@ -198,12 +198,11 @@ describe('Entity cache inconsistency', () => {
|
||||
createFullIntegrationTestEntityCompanionProvider(knexInstance, genericRedisCacheContext),
|
||||
);
|
||||
|
||||
const loadedById = await TestEntity.loader(viewerContextLast)
|
||||
.enforcing()
|
||||
.loadByIDAsync(entity1.getID());
|
||||
const loadedByField = await TestEntity.loader(viewerContextLast)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('other_string', 'hello');
|
||||
const loadedById = await TestEntity.loader(viewerContextLast).loadByIDAsync(entity1.getID());
|
||||
const loadedByField = await TestEntity.loader(viewerContextLast).loadByFieldEqualingAsync(
|
||||
'other_string',
|
||||
'hello',
|
||||
);
|
||||
|
||||
expect(loadedById.getField('third_string')).toEqual('updated');
|
||||
expect(loadedByField!.getField('third_string')).toEqual('updated');
|
||||
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
import {
|
||||
EntityPrivacyPolicy,
|
||||
ViewerContext,
|
||||
AlwaysAllowPrivacyPolicyRule,
|
||||
Entity,
|
||||
EntityCompanionDefinition,
|
||||
EntityConfiguration,
|
||||
StringField,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
import {
|
||||
GenericRedisCacheContext,
|
||||
RedisCacheInvalidationStrategy,
|
||||
} from '@expo/entity-cache-adapter-redis';
|
||||
import Redis from 'ioredis';
|
||||
import { knex, Knex } from 'knex';
|
||||
import nullthrows from 'nullthrows';
|
||||
import { URL } from 'url';
|
||||
|
||||
import { createFullIntegrationTestEntityCompanionProvider } from '../__testfixtures__/createFullIntegrationTestEntityCompanionProvider';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
||||
function createTestEntityDefinitonWithCacheKeyVersion(cacheKeyVersion: number) {
|
||||
interface TestFields {
|
||||
id: string;
|
||||
string_field: string;
|
||||
}
|
||||
|
||||
class TestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
TestFields,
|
||||
'id',
|
||||
ViewerContext,
|
||||
TestEntity
|
||||
> {
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, 'id', ViewerContext, TestEntity>(),
|
||||
];
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, 'id', ViewerContext, TestEntity>(),
|
||||
];
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, 'id', ViewerContext, TestEntity>(),
|
||||
];
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, 'id', ViewerContext, TestEntity>(),
|
||||
];
|
||||
}
|
||||
|
||||
class TestEntity extends Entity<TestFields, 'id', ViewerContext> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
TestFields,
|
||||
'id',
|
||||
ViewerContext,
|
||||
TestEntity,
|
||||
TestEntityPrivacyPolicy
|
||||
> {
|
||||
return {
|
||||
entityClass: TestEntity,
|
||||
entityConfiguration: testEntityConfiguration,
|
||||
privacyPolicyClass: TestEntityPrivacyPolicy,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const testEntityConfiguration = new EntityConfiguration<TestFields, 'id'>({
|
||||
idField: 'id',
|
||||
tableName: 'testentities',
|
||||
cacheKeyVersion,
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
string_field: new StringField({
|
||||
columnName: 'string_field',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
});
|
||||
|
||||
return { TestEntity };
|
||||
}
|
||||
|
||||
async function createOrTruncatePostgresTablesAsync(knex: Knex): Promise<void> {
|
||||
await knex.schema.createTable('testentities', (table) => {
|
||||
table.uuid('id').defaultTo(knex.raw('gen_random_uuid()')).primary();
|
||||
table.string('string_field').notNullable();
|
||||
});
|
||||
await knex.into('testentities').truncate();
|
||||
}
|
||||
|
||||
async function dropPostgresTableAsync(knex: Knex): Promise<void> {
|
||||
if (await knex.schema.hasTable('testentities')) {
|
||||
await knex.schema.dropTable('testentities');
|
||||
}
|
||||
}
|
||||
|
||||
describe('Lack of entity cache push safety with RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION', () => {
|
||||
let knexInstance: Knex;
|
||||
const redisClient = new Redis(new URL(process.env['REDIS_URL']!).toString());
|
||||
let genericRedisCacheContext: GenericRedisCacheContext;
|
||||
|
||||
beforeAll(() => {
|
||||
knexInstance = knex({
|
||||
client: 'pg',
|
||||
connection: {
|
||||
user: nullthrows(process.env['PGUSER']),
|
||||
password: nullthrows(process.env['PGPASSWORD']),
|
||||
host: 'localhost',
|
||||
port: parseInt(nullthrows(process.env['PGPORT']), 10),
|
||||
database: nullthrows(process.env['PGDATABASE']),
|
||||
},
|
||||
});
|
||||
genericRedisCacheContext = {
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
part.replace('\\', '\\\\').replace(delimiter, `\\${delimiter}`),
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
},
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
};
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await createOrTruncatePostgresTablesAsync(knexInstance);
|
||||
await redisClient.flushdb();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await dropPostgresTableAsync(knexInstance);
|
||||
await knexInstance.destroy();
|
||||
redisClient.disconnect();
|
||||
});
|
||||
|
||||
it('does not cross-invalidates cache and thus has cache inconsistency', async () => {
|
||||
const preDeployCacheKeyVersion = 1;
|
||||
const newCacheKeyVersion = 2;
|
||||
|
||||
const { TestEntity: TestEntityPreDeploy } =
|
||||
createTestEntityDefinitonWithCacheKeyVersion(preDeployCacheKeyVersion);
|
||||
const { TestEntity: TestEntityNew } =
|
||||
createTestEntityDefinitonWithCacheKeyVersion(newCacheKeyVersion);
|
||||
|
||||
// Simulate a deploy of the app with a new cache key version. Old code version is still running on some machines and new code version is running on others.
|
||||
// This test is designed to simulate the worst case cache poisoning scenario during cache version changes.
|
||||
|
||||
// request 1 creates and loads an entity on the old code version, caching it in cache key version 1
|
||||
const viewerContextRequest1 = new ViewerContext(
|
||||
createFullIntegrationTestEntityCompanionProvider(knexInstance, genericRedisCacheContext),
|
||||
);
|
||||
const entityReq1 = await TestEntityPreDeploy.creator(viewerContextRequest1)
|
||||
.setField('string_field', 'req1')
|
||||
.createAsync();
|
||||
const entityId = entityReq1.getID();
|
||||
const entityReq1Loaded =
|
||||
await TestEntityPreDeploy.loader(viewerContextRequest1).loadByIDAsync(entityId);
|
||||
expect(entityReq1Loaded).not.toBeNull();
|
||||
|
||||
// request 2 loads the entity in the new code version (caching it in cache key version 2), updates it (invalidating in 2), and loads it again (caching it in cache key version 2)
|
||||
const viewerContextRequest2 = new ViewerContext(
|
||||
createFullIntegrationTestEntityCompanionProvider(knexInstance, genericRedisCacheContext),
|
||||
);
|
||||
const entityReq2 = await TestEntityNew.loader(viewerContextRequest2).loadByIDAsync(entityId);
|
||||
expect(entityReq2.getField('string_field')).toBe('req1');
|
||||
await TestEntityNew.updater(entityReq2).setField('string_field', 'req2').updateAsync();
|
||||
const entityReq2UpdatedLoaded =
|
||||
await TestEntityNew.loader(viewerContextRequest2).loadByIDAsync(entityId);
|
||||
expect(entityReq2UpdatedLoaded).not.toBeNull();
|
||||
|
||||
// request 3 loads the entity in the old code version (loading it from cache key version 1)
|
||||
const viewerContextRequest3 = new ViewerContext(
|
||||
createFullIntegrationTestEntityCompanionProvider(knexInstance, genericRedisCacheContext),
|
||||
);
|
||||
const entityReq3 =
|
||||
await TestEntityPreDeploy.loader(viewerContextRequest3).loadByIDAsync(entityId);
|
||||
|
||||
// in a consistent system this would be req2. This fails due to lack of cross-invalidation since the cache for pre-deploy is stale and wasn't invalidated.
|
||||
expect(entityReq3.getField('string_field')).toBe('req1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Entity cache push safety with RedisCacheInvalidationStrategy.SURROUNDING_CACHE_KEY_VERSIONS', () => {
|
||||
let knexInstance: Knex;
|
||||
const redisClient = new Redis(new URL(process.env['REDIS_URL']!).toString());
|
||||
let genericRedisCacheContext: GenericRedisCacheContext;
|
||||
|
||||
beforeAll(() => {
|
||||
knexInstance = knex({
|
||||
client: 'pg',
|
||||
connection: {
|
||||
user: nullthrows(process.env['PGUSER']),
|
||||
password: nullthrows(process.env['PGPASSWORD']),
|
||||
host: 'localhost',
|
||||
port: parseInt(nullthrows(process.env['PGPORT']), 10),
|
||||
database: nullthrows(process.env['PGDATABASE']),
|
||||
},
|
||||
});
|
||||
genericRedisCacheContext = {
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
part.replace('\\', '\\\\').replace(delimiter, `\\${delimiter}`),
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
},
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.SURROUNDING_CACHE_KEY_VERSIONS,
|
||||
};
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await createOrTruncatePostgresTablesAsync(knexInstance);
|
||||
await redisClient.flushdb();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await dropPostgresTableAsync(knexInstance);
|
||||
await knexInstance.destroy();
|
||||
redisClient.disconnect();
|
||||
});
|
||||
|
||||
it('correctly cross-invalidates cache with new and old code (cache key) versions', async () => {
|
||||
const preDeployCacheKeyVersion = 1;
|
||||
const newCacheKeyVersion = 2;
|
||||
|
||||
const { TestEntity: TestEntityPreDeploy } =
|
||||
createTestEntityDefinitonWithCacheKeyVersion(preDeployCacheKeyVersion);
|
||||
const { TestEntity: TestEntityNew } =
|
||||
createTestEntityDefinitonWithCacheKeyVersion(newCacheKeyVersion);
|
||||
|
||||
// Simulate a deploy of the app with a new cache key version. Old code version is still running on some machines and new code version is running on others.
|
||||
// This test is designed to simulate the worst case cache poisoning scenario during cache version changes.
|
||||
|
||||
// request 1 creates and loads an entity on the old code version, caching it in cache key version 1
|
||||
const viewerContextRequest1 = new ViewerContext(
|
||||
createFullIntegrationTestEntityCompanionProvider(knexInstance, genericRedisCacheContext),
|
||||
);
|
||||
const entityReq1 = await TestEntityPreDeploy.creator(viewerContextRequest1)
|
||||
.setField('string_field', 'req1')
|
||||
.createAsync();
|
||||
const entityId = entityReq1.getID();
|
||||
const entityReq1Loaded =
|
||||
await TestEntityPreDeploy.loader(viewerContextRequest1).loadByIDAsync(entityId);
|
||||
expect(entityReq1Loaded).not.toBeNull();
|
||||
|
||||
// request 2 loads the entity in the new code version (caching it in cache key version 2), updates it (invalidating in both 1 and 2), and loads it again (caching it in cache key version 2)
|
||||
const viewerContextRequest2 = new ViewerContext(
|
||||
createFullIntegrationTestEntityCompanionProvider(knexInstance, genericRedisCacheContext),
|
||||
);
|
||||
const entityReq2 = await TestEntityNew.loader(viewerContextRequest2).loadByIDAsync(entityId);
|
||||
expect(entityReq2.getField('string_field')).toBe('req1');
|
||||
await TestEntityNew.updater(entityReq2).setField('string_field', 'req2').updateAsync();
|
||||
const entityReq2UpdatedLoaded =
|
||||
await TestEntityNew.loader(viewerContextRequest2).loadByIDAsync(entityId);
|
||||
expect(entityReq2UpdatedLoaded).not.toBeNull();
|
||||
|
||||
// request 3 loads the entity in the old code version (caching it in cache key version 1), updates it (invalidating in both 1 and 2), and loads it again (caching it in cache key version 1)
|
||||
const viewerContextRequest3 = new ViewerContext(
|
||||
createFullIntegrationTestEntityCompanionProvider(knexInstance, genericRedisCacheContext),
|
||||
);
|
||||
const entityReq3 =
|
||||
await TestEntityPreDeploy.loader(viewerContextRequest3).loadByIDAsync(entityId);
|
||||
expect(entityReq3.getField('string_field')).toBe('req2'); // this would fail if cross-invalidation were not implemented since the cache for pre-deploy would be stale
|
||||
await TestEntityPreDeploy.updater(entityReq3).setField('string_field', 'req3').updateAsync();
|
||||
const entityReq3UpdatedLoaded =
|
||||
await TestEntityPreDeploy.loader(viewerContextRequest3).loadByIDAsync(entityId);
|
||||
expect(entityReq3UpdatedLoaded).not.toBeNull();
|
||||
|
||||
// request 4 loads the entity in the new code version
|
||||
const viewerContextRequest4 = new ViewerContext(
|
||||
createFullIntegrationTestEntityCompanionProvider(knexInstance, genericRedisCacheContext),
|
||||
);
|
||||
const entityReq4 = await TestEntityNew.loader(viewerContextRequest4).loadByIDAsync(entityId);
|
||||
expect(entityReq4.getField('string_field')).toBe('req3');
|
||||
expect(entityReq4).not.toBeNull();
|
||||
});
|
||||
});
|
||||
+12
-11
@@ -1,5 +1,8 @@
|
||||
import { ViewerContext } from '@expo/entity';
|
||||
import { GenericRedisCacheContext } from '@expo/entity-cache-adapter-redis';
|
||||
import {
|
||||
GenericRedisCacheContext,
|
||||
RedisCacheInvalidationStrategy,
|
||||
} from '@expo/entity-cache-adapter-redis';
|
||||
import Redis from 'ioredis';
|
||||
import { knex, Knex } from 'knex';
|
||||
import nullthrows from 'nullthrows';
|
||||
@@ -7,7 +10,7 @@ import { URL } from 'url';
|
||||
|
||||
import ChildEntity from './entities/ChildEntity';
|
||||
import ParentEntity from './entities/ParentEntity';
|
||||
import { createFullIntegrationTestEntityCompanionProvider } from '../testfixtures/createFullIntegrationTestEntityCompanionProvider';
|
||||
import { createFullIntegrationTestEntityCompanionProvider } from '../__testfixtures__/createFullIntegrationTestEntityCompanionProvider';
|
||||
|
||||
async function createOrTruncatePostgresTablesAsync(knex: Knex): Promise<void> {
|
||||
await knex.schema.createTable('parents', (table) => {
|
||||
@@ -59,6 +62,7 @@ describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -79,29 +83,26 @@ describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
|
||||
createFullIntegrationTestEntityCompanionProvider(knexInstance, genericRedisCacheContext),
|
||||
);
|
||||
|
||||
const parent = await ParentEntity.creator(viewerContext).enforcing().createAsync();
|
||||
const parent = await ParentEntity.creator(viewerContext).createAsync();
|
||||
const child = await ChildEntity.creator(viewerContext)
|
||||
.enforcing()
|
||||
.setField('parent_id', parent.getID())
|
||||
.createAsync();
|
||||
|
||||
await expect(
|
||||
ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID()),
|
||||
ParentEntity.loader(viewerContext).loadByIDNullableAsync(parent.getID()),
|
||||
).resolves.not.toBeNull();
|
||||
await expect(
|
||||
ChildEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('parent_id', parent.getID()),
|
||||
ChildEntity.loader(viewerContext).loadByFieldEqualingAsync('parent_id', parent.getID()),
|
||||
).resolves.not.toBeNull();
|
||||
|
||||
await ParentEntity.deleter(parent).enforcing().deleteAsync();
|
||||
await ParentEntity.deleter(parent).deleteAsync();
|
||||
|
||||
await expect(
|
||||
ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID()),
|
||||
ParentEntity.loader(viewerContext).loadByIDNullableAsync(parent.getID()),
|
||||
).resolves.toBeNull();
|
||||
|
||||
await expect(
|
||||
ChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(child.getID()),
|
||||
ChildEntity.loader(viewerContext).loadByIDNullableAsync(child.getID()),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
+17
-15
@@ -7,14 +7,17 @@ import {
|
||||
EntityConfiguration,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
import { GenericRedisCacheContext } from '@expo/entity-cache-adapter-redis';
|
||||
import {
|
||||
GenericRedisCacheContext,
|
||||
RedisCacheInvalidationStrategy,
|
||||
} from '@expo/entity-cache-adapter-redis';
|
||||
import Redis from 'ioredis';
|
||||
import { knex, Knex } from 'knex';
|
||||
import nullthrows from 'nullthrows';
|
||||
import { URL } from 'url';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import { createFullIntegrationTestEntityCompanionProvider } from '../testfixtures/createFullIntegrationTestEntityCompanionProvider';
|
||||
import { createFullIntegrationTestEntityCompanionProvider } from '../__testfixtures__/createFullIntegrationTestEntityCompanionProvider';
|
||||
|
||||
interface TestFields {
|
||||
id: string;
|
||||
@@ -22,28 +25,28 @@ interface TestFields {
|
||||
|
||||
class TestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
TestFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
TestEntity
|
||||
> {
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, string, ViewerContext, TestEntity>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, 'id', ViewerContext, TestEntity>(),
|
||||
];
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, string, ViewerContext, TestEntity>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, 'id', ViewerContext, TestEntity>(),
|
||||
];
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, string, ViewerContext, TestEntity>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, 'id', ViewerContext, TestEntity>(),
|
||||
];
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, string, ViewerContext, TestEntity>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<TestFields, 'id', ViewerContext, TestEntity>(),
|
||||
];
|
||||
}
|
||||
|
||||
class TestEntity extends Entity<TestFields, string, ViewerContext> {
|
||||
class TestEntity extends Entity<TestFields, 'id', ViewerContext> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
TestFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
TestEntity,
|
||||
TestEntityPrivacyPolicy
|
||||
@@ -56,7 +59,7 @@ class TestEntity extends Entity<TestFields, string, ViewerContext> {
|
||||
}
|
||||
}
|
||||
|
||||
const testEntityConfiguration = new EntityConfiguration<TestFields>({
|
||||
const testEntityConfiguration = new EntityConfiguration<TestFields, 'id'>({
|
||||
idField: 'id',
|
||||
tableName: 'testentities',
|
||||
schema: {
|
||||
@@ -110,6 +113,7 @@ describe('Entity integrity', () => {
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -129,10 +133,10 @@ describe('Entity integrity', () => {
|
||||
createFullIntegrationTestEntityCompanionProvider(knexInstance, genericRedisCacheContext),
|
||||
);
|
||||
|
||||
const entity1 = await TestEntity.creator(viewerContext).enforcing().createAsync();
|
||||
const entity1 = await TestEntity.creator(viewerContext).createAsync();
|
||||
|
||||
await expect(
|
||||
TestEntity.updater(entity1).enforcing().setField('id', uuidv4()).updateAsync(),
|
||||
TestEntity.updater(entity1).setField('id', uuidv4()).updateAsync(),
|
||||
).rejects.toThrow('id field updates not supported: (entityClass = TestEntity)');
|
||||
|
||||
// ensure cache consistency
|
||||
@@ -140,9 +144,7 @@ describe('Entity integrity', () => {
|
||||
createFullIntegrationTestEntityCompanionProvider(knexInstance, genericRedisCacheContext),
|
||||
);
|
||||
|
||||
const loadedById = await TestEntity.loader(viewerContextLast)
|
||||
.enforcing()
|
||||
.loadByIDAsync(entity1.getID());
|
||||
const loadedById = await TestEntity.loader(viewerContextLast).loadByIDAsync(entity1.getID());
|
||||
|
||||
expect(loadedById.getID()).toEqual(entity1.getID());
|
||||
});
|
||||
|
||||
+29
-27
@@ -8,14 +8,17 @@ import {
|
||||
UUIDField,
|
||||
EntityEdgeDeletionBehavior,
|
||||
} from '@expo/entity';
|
||||
import { GenericRedisCacheContext } from '@expo/entity-cache-adapter-redis';
|
||||
import {
|
||||
GenericRedisCacheContext,
|
||||
RedisCacheInvalidationStrategy,
|
||||
} from '@expo/entity-cache-adapter-redis';
|
||||
import Redis from 'ioredis';
|
||||
import { knex, Knex } from 'knex';
|
||||
import nullthrows from 'nullthrows';
|
||||
import { URL } from 'url';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import { createFullIntegrationTestEntityCompanionProvider } from '../testfixtures/createFullIntegrationTestEntityCompanionProvider';
|
||||
import { createFullIntegrationTestEntityCompanionProvider } from '../__testfixtures__/createFullIntegrationTestEntityCompanionProvider';
|
||||
|
||||
interface CategoryFields {
|
||||
id: string;
|
||||
@@ -27,18 +30,18 @@ interface OtherFields {
|
||||
parent_category_id: string;
|
||||
}
|
||||
|
||||
class PrivacyPolicy extends EntityPrivacyPolicy<any, string, ViewerContext, any> {
|
||||
class PrivacyPolicy extends EntityPrivacyPolicy<any, 'id', ViewerContext, any> {
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<any, string, ViewerContext, any>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<any, 'id', ViewerContext, any>(),
|
||||
];
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<any, string, ViewerContext, any>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<any, 'id', ViewerContext, any>(),
|
||||
];
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<any, string, ViewerContext, any>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<any, 'id', ViewerContext, any>(),
|
||||
];
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<any, string, ViewerContext, any>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<any, 'id', ViewerContext, any>(),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -47,10 +50,10 @@ const makeEntityClasses = async (knex: Knex, edgeDeletionBehavior: EntityEdgeDel
|
||||
const categoriesTableName = uuidv4();
|
||||
const othersTableName = uuidv4();
|
||||
|
||||
class CategoryEntity extends Entity<CategoryFields, string, ViewerContext> {
|
||||
class CategoryEntity extends Entity<CategoryFields, 'id', ViewerContext> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
CategoryFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
CategoryEntity,
|
||||
PrivacyPolicy
|
||||
@@ -63,10 +66,10 @@ const makeEntityClasses = async (knex: Knex, edgeDeletionBehavior: EntityEdgeDel
|
||||
}
|
||||
}
|
||||
|
||||
class OtherEntity extends Entity<OtherFields, string, ViewerContext> {
|
||||
class OtherEntity extends Entity<OtherFields, 'id', ViewerContext> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
OtherFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
OtherEntity,
|
||||
PrivacyPolicy
|
||||
@@ -79,7 +82,7 @@ const makeEntityClasses = async (knex: Knex, edgeDeletionBehavior: EntityEdgeDel
|
||||
}
|
||||
}
|
||||
|
||||
const categoryEntityConfiguration = new EntityConfiguration<CategoryFields>({
|
||||
const categoryEntityConfiguration = new EntityConfiguration<CategoryFields, 'id'>({
|
||||
idField: 'id',
|
||||
tableName: categoriesTableName,
|
||||
inboundEdges: [OtherEntity],
|
||||
@@ -101,7 +104,7 @@ const makeEntityClasses = async (knex: Knex, edgeDeletionBehavior: EntityEdgeDel
|
||||
cacheAdapterFlavor: 'redis',
|
||||
});
|
||||
|
||||
const otherEntityConfiguration = new EntityConfiguration<OtherFields>({
|
||||
const otherEntityConfiguration = new EntityConfiguration<OtherFields, 'id'>({
|
||||
idField: 'id',
|
||||
tableName: othersTableName,
|
||||
inboundEdges: [CategoryEntity],
|
||||
@@ -198,6 +201,7 @@ describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -221,40 +225,38 @@ describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
|
||||
createFullIntegrationTestEntityCompanionProvider(knexInstance, genericRedisCacheContext),
|
||||
);
|
||||
|
||||
const category1 = await CategoryEntity.creator(viewerContext).enforcing().createAsync();
|
||||
const category1 = await CategoryEntity.creator(viewerContext).createAsync();
|
||||
const other1 = await OtherEntity.creator(viewerContext)
|
||||
.enforcing()
|
||||
.setField('parent_category_id', category1.getID())
|
||||
.createAsync();
|
||||
await CategoryEntity.updater(category1)
|
||||
.enforcing()
|
||||
.setField('parent_other_id', other1.getID())
|
||||
.updateAsync();
|
||||
|
||||
await CategoryEntity.deleter(category1).enforcing().deleteAsync();
|
||||
await CategoryEntity.deleter(category1).deleteAsync();
|
||||
|
||||
if (edgeDeletionBehavior === EntityEdgeDeletionBehavior.SET_NULL) {
|
||||
await expect(
|
||||
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(category1.getID()),
|
||||
CategoryEntity.loader(viewerContext).loadByIDNullableAsync(category1.getID()),
|
||||
).resolves.toBeNull();
|
||||
const otherLoaded = await OtherEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadByIDNullableAsync(other1.getID());
|
||||
const otherLoaded = await OtherEntity.loader(viewerContext).loadByIDNullableAsync(
|
||||
other1.getID(),
|
||||
);
|
||||
expect(otherLoaded?.getField('parent_category_id')).toBeNull();
|
||||
} else if (edgeDeletionBehavior === EntityEdgeDeletionBehavior.SET_NULL_INVALIDATE_CACHE_ONLY) {
|
||||
await expect(
|
||||
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(category1.getID()),
|
||||
CategoryEntity.loader(viewerContext).loadByIDNullableAsync(category1.getID()),
|
||||
).resolves.toBeNull();
|
||||
const otherLoaded = await OtherEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadByIDNullableAsync(other1.getID());
|
||||
const otherLoaded = await OtherEntity.loader(viewerContext).loadByIDNullableAsync(
|
||||
other1.getID(),
|
||||
);
|
||||
expect(otherLoaded?.getField('parent_category_id')).toBeNull();
|
||||
} else {
|
||||
await expect(
|
||||
CategoryEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(category1.getID()),
|
||||
CategoryEntity.loader(viewerContext).loadByIDNullableAsync(category1.getID()),
|
||||
).resolves.toBeNull();
|
||||
await expect(
|
||||
OtherEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(other1.getID()),
|
||||
OtherEntity.loader(viewerContext).loadByIDNullableAsync(other1.getID()),
|
||||
).resolves.toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
+8
-8
@@ -16,32 +16,32 @@ interface ChildFields {
|
||||
parent_id: string;
|
||||
}
|
||||
|
||||
class TestEntityPrivacyPolicy extends EntityPrivacyPolicy<any, string, ViewerContext, any, any> {
|
||||
class TestEntityPrivacyPolicy extends EntityPrivacyPolicy<any, 'id', ViewerContext, any, any> {
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<any, string, ViewerContext, any, any>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<any, 'id', ViewerContext, any, any>(),
|
||||
];
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<any, string, ViewerContext, any, any>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<any, 'id', ViewerContext, any, any>(),
|
||||
];
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<any, string, ViewerContext, any, any>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<any, 'id', ViewerContext, any, any>(),
|
||||
];
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<any, string, ViewerContext, any, any>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<any, 'id', ViewerContext, any, any>(),
|
||||
];
|
||||
}
|
||||
|
||||
export default class ChildEntity extends Entity<ChildFields, string, ViewerContext> {
|
||||
export default class ChildEntity extends Entity<ChildFields, 'id', ViewerContext> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
ChildFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
ChildEntity,
|
||||
TestEntityPrivacyPolicy
|
||||
> {
|
||||
return {
|
||||
entityClass: ChildEntity,
|
||||
entityConfiguration: new EntityConfiguration<ChildFields>({
|
||||
entityConfiguration: new EntityConfiguration<ChildFields, 'id'>({
|
||||
idField: 'id',
|
||||
tableName: 'children',
|
||||
schema: {
|
||||
|
||||
+8
-8
@@ -14,32 +14,32 @@ interface ParentFields {
|
||||
id: string;
|
||||
}
|
||||
|
||||
class TestEntityPrivacyPolicy extends EntityPrivacyPolicy<any, string, ViewerContext, any, any> {
|
||||
class TestEntityPrivacyPolicy extends EntityPrivacyPolicy<any, 'id', ViewerContext, any, any> {
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<any, string, ViewerContext, any, any>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<any, 'id', ViewerContext, any, any>(),
|
||||
];
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<any, string, ViewerContext, any, any>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<any, 'id', ViewerContext, any, any>(),
|
||||
];
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<any, string, ViewerContext, any, any>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<any, 'id', ViewerContext, any, any>(),
|
||||
];
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<any, string, ViewerContext, any, any>(),
|
||||
new AlwaysAllowPrivacyPolicyRule<any, 'id', ViewerContext, any, any>(),
|
||||
];
|
||||
}
|
||||
|
||||
export default class ParentEntity extends Entity<ParentFields, string, ViewerContext> {
|
||||
export default class ParentEntity extends Entity<ParentFields, 'id', ViewerContext> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
ParentFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
ParentEntity,
|
||||
TestEntityPrivacyPolicy
|
||||
> {
|
||||
return {
|
||||
entityClass: ParentEntity,
|
||||
entityConfiguration: new EntityConfiguration<ParentFields>({
|
||||
entityConfiguration: new EntityConfiguration<ParentFields, 'id'>({
|
||||
idField: 'id',
|
||||
tableName: 'parents',
|
||||
inboundEdges: [ChildEntity],
|
||||
|
||||
File renamed without changes.
@@ -0,0 +1 @@
|
||||
// placeholder file to fix tsc
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"extends": "../../tsconfig.build.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
}
|
||||
}
|
||||
@@ -3,5 +3,4 @@
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -3,6 +3,42 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.44.0](https://github.com/expo/entity/compare/v0.43.0...v0.44.0) (2025-05-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.43.0](https://github.com/expo/entity/compare/v0.42.0...v0.43.0) (2025-04-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.42.0](https://github.com/expo/entity/compare/v0.41.0...v0.42.0) (2025-04-10)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add @expo/entity-testing-utils package ([#280](https://github.com/expo/entity/issues/280)) ([485894a](https://github.com/expo/entity/commit/485894af16e233d533a9480285bbda56812cbe0b))
|
||||
* enforce explicit id field cache property ([#276](https://github.com/expo/entity/issues/276)) ([1da5cc0](https://github.com/expo/entity/commit/1da5cc01e1affc3b3338a0ab2050504b5853ac6f))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.41.0](https://github.com/expo/entity/compare/v0.40.0...v0.41.0) (2025-03-07)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.40.0](https://github.com/expo/entity/compare/v0.39.0...v0.40.0) (2025-02-27)
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
# @expo/entity-ip-address-field
|
||||
|
||||
A package containing the IP address EntityField definitions for @expo/entity. Supports addresses with either IPv4 or IPv6 syntax.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity-ip-address-field",
|
||||
"version": "0.40.0",
|
||||
"version": "0.44.0",
|
||||
"description": "IP address EntityField definitions for @expo/entity",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -10,6 +10,7 @@
|
||||
"types": "build/index.d.ts",
|
||||
"scripts": {
|
||||
"tsc": "tsc",
|
||||
"build": "tsc -b tsconfig.build.json",
|
||||
"clean": "rm -rf build coverage coverage-integration",
|
||||
"lint": "eslint src",
|
||||
"lint-fix": "eslint src --fix",
|
||||
@@ -26,21 +27,21 @@
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@expo/entity": "workspace:^",
|
||||
"ip-address": "^8.1.0"
|
||||
"ip-address": "^10.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/jsbn": "^1.2.29",
|
||||
"@expo/entity-testing-utils": "workspace:^",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^20.14.1",
|
||||
"ctix": "^2.7.0",
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-config-universe": "^14.0.0",
|
||||
"eslint-plugin-tsdoc": "^0.3.0",
|
||||
"eslint": "^9.26.0",
|
||||
"eslint-config-universe": "^15.0.3",
|
||||
"eslint-plugin-tsdoc": "^0.4.0",
|
||||
"jest": "^29.7.0",
|
||||
"prettier": "^3.3.3",
|
||||
"prettier": "^3.5.3",
|
||||
"prettier-plugin-organize-imports": "^4.1.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-jest": "^29.3.2",
|
||||
"ts-mockito": "^2.6.1",
|
||||
"typescript": "^5.7.3"
|
||||
"typescript": "^5.8.3"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import { EntityFieldDefinition } from '@expo/entity';
|
||||
import { Address4, Address6 } from 'ip-address';
|
||||
|
||||
export class IPAddressField extends EntityFieldDefinition<string> {
|
||||
export class IPAddressField<TRequireExplicitCache extends boolean> extends EntityFieldDefinition<
|
||||
string,
|
||||
TRequireExplicitCache
|
||||
> {
|
||||
protected validateInputValueInternal(value: string): boolean {
|
||||
return Address4.isValid(value) || Address6.isValid(value);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describeFieldTestCase } from '@expo/entity';
|
||||
import { describeFieldTestCase } from '@expo/entity-testing-utils';
|
||||
|
||||
import { IPAddressField } from '../EntityFields';
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.build.json",
|
||||
"include": ["src"],
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "build",
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -3,6 +3,49 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.44.0](https://github.com/expo/entity/compare/v0.43.0...v0.44.0) (2025-05-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-local-memory
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.43.0](https://github.com/expo/entity/compare/v0.42.0...v0.43.0) (2025-04-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-local-memory
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.42.0](https://github.com/expo/entity/compare/v0.41.0...v0.42.0) (2025-04-10)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add @expo/entity-testing-utils package ([#280](https://github.com/expo/entity/issues/280)) ([485894a](https://github.com/expo/entity/commit/485894af16e233d533a9480285bbda56812cbe0b))
|
||||
* change entity id field generic to field name and derive type where necessary ([#278](https://github.com/expo/entity/issues/278)) ([b7e524c](https://github.com/expo/entity/commit/b7e524c41892797608d0b884410b8d520a80a9ef))
|
||||
* enforce explicit id field cache property ([#276](https://github.com/expo/entity/issues/276)) ([1da5cc0](https://github.com/expo/entity/commit/1da5cc01e1affc3b3338a0ab2050504b5853ac6f))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.41.0](https://github.com/expo/entity/compare/v0.40.0...v0.41.0) (2025-03-07)
|
||||
|
||||
|
||||
* feat!: Default all loaders and mutators to enforcing (#256) ([a976e76](https://github.com/expo/entity/commit/a976e765098bca27049585e43a3bed5c71b9ac6b)), closes [#256](https://github.com/expo/entity/issues/256)
|
||||
|
||||
|
||||
### BREAKING CHANGES
|
||||
|
||||
* Default all loaders and mutators to enforcing
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.40.0](https://github.com/expo/entity/compare/v0.39.0...v0.40.0) (2025-02-27)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity-secondary-cache-local-memory",
|
||||
"version": "0.40.0",
|
||||
"version": "0.44.0",
|
||||
"description": "Local memory secondary cache for @expo/entity",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -10,6 +10,7 @@
|
||||
"types": "build/index.d.ts",
|
||||
"scripts": {
|
||||
"tsc": "tsc",
|
||||
"build": "tsc -b tsconfig.build.json",
|
||||
"clean": "rm -rf build coverage coverage-integration",
|
||||
"lint": "eslint src",
|
||||
"lint-fix": "eslint src --fix",
|
||||
@@ -31,18 +32,18 @@
|
||||
"@expo/entity-cache-adapter-local-memory": "workspace:^"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^20.14.1",
|
||||
"ctix": "^2.7.0",
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-config-universe": "^14.0.0",
|
||||
"eslint-plugin-tsdoc": "^0.3.0",
|
||||
"eslint": "^9.26.0",
|
||||
"eslint-config-universe": "^15.0.3",
|
||||
"eslint-plugin-tsdoc": "^0.4.0",
|
||||
"jest": "^29.7.0",
|
||||
"nullthrows": "^1.1.1",
|
||||
"prettier": "^3.3.3",
|
||||
"prettier": "^3.5.3",
|
||||
"prettier-plugin-organize-imports": "^4.1.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-jest": "^29.3.2",
|
||||
"ts-mockito": "^2.6.1",
|
||||
"typescript": "^5.7.3"
|
||||
"typescript": "^5.8.3"
|
||||
}
|
||||
}
|
||||
@@ -13,10 +13,11 @@ import {
|
||||
*/
|
||||
export default class LocalMemorySecondaryEntityCache<
|
||||
TFields extends Record<string, any>,
|
||||
TIDField extends keyof TFields,
|
||||
TLoadParams,
|
||||
> extends GenericSecondaryEntityCache<TFields, TLoadParams> {
|
||||
> extends GenericSecondaryEntityCache<TFields, TIDField, TLoadParams> {
|
||||
constructor(
|
||||
entityConfiguration: EntityConfiguration<TFields>,
|
||||
entityConfiguration: EntityConfiguration<TFields, TIDField>,
|
||||
localMemoryCache: LocalMemoryCache<TFields>,
|
||||
) {
|
||||
super(new GenericLocalMemoryCacher(entityConfiguration, localMemoryCache), (params) =>
|
||||
|
||||
+30
-29
@@ -5,20 +5,19 @@ import {
|
||||
NoOpEntityMetricsAdapter,
|
||||
IEntityMetricsAdapter,
|
||||
EntityCompanionProvider,
|
||||
StubQueryContextProvider,
|
||||
StubDatabaseAdapterProvider,
|
||||
AlwaysAllowPrivacyPolicyRule,
|
||||
EntityPrivacyPolicy,
|
||||
UUIDField,
|
||||
StringField,
|
||||
EntityConfiguration,
|
||||
EntityCompanionDefinition,
|
||||
Entity,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
import {
|
||||
GenericLocalMemoryCacher,
|
||||
LocalMemoryCacheAdapterProvider,
|
||||
} from '@expo/entity-cache-adapter-local-memory';
|
||||
import { StubQueryContextProvider, StubDatabaseAdapterProvider } from '@expo/entity-testing-utils';
|
||||
import nullthrows from 'nullthrows';
|
||||
|
||||
import LocalMemorySecondaryEntityCache from '../LocalMemorySecondaryEntityCache';
|
||||
@@ -30,12 +29,12 @@ export type LocalMemoryTestEntityFields = {
|
||||
|
||||
export default class LocalMemoryTestEntity extends Entity<
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext
|
||||
> {
|
||||
static defineCompanionDefinition(): EntityCompanionDefinition<
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
LocalMemoryTestEntity,
|
||||
LocalMemoryTestEntityPrivacyPolicy
|
||||
@@ -50,14 +49,14 @@ export default class LocalMemoryTestEntity extends Entity<
|
||||
|
||||
export class LocalMemoryTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
LocalMemoryTestEntity
|
||||
> {
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
LocalMemoryTestEntity
|
||||
>(),
|
||||
@@ -65,7 +64,7 @@ export class LocalMemoryTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
LocalMemoryTestEntity
|
||||
>(),
|
||||
@@ -73,7 +72,7 @@ export class LocalMemoryTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
LocalMemoryTestEntity
|
||||
>(),
|
||||
@@ -81,28 +80,31 @@ export class LocalMemoryTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
ViewerContext,
|
||||
LocalMemoryTestEntity
|
||||
>(),
|
||||
];
|
||||
}
|
||||
|
||||
export const localMemoryTestEntityConfiguration =
|
||||
new EntityConfiguration<LocalMemoryTestEntityFields>({
|
||||
idField: 'id',
|
||||
tableName: 'local_memory_test_entities',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
}),
|
||||
name: new StringField({
|
||||
columnName: 'name',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'local-memory',
|
||||
});
|
||||
export const localMemoryTestEntityConfiguration = new EntityConfiguration<
|
||||
LocalMemoryTestEntityFields,
|
||||
'id'
|
||||
>({
|
||||
idField: 'id',
|
||||
tableName: 'local_memory_test_entities',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: false,
|
||||
}),
|
||||
name: new StringField({
|
||||
columnName: 'name',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'local-memory',
|
||||
});
|
||||
|
||||
const queryContextProvider = new StubQueryContextProvider();
|
||||
|
||||
@@ -140,7 +142,7 @@ const FAKE_ID = 'fake';
|
||||
class TestSecondaryLocalMemoryCacheLoader extends EntitySecondaryCacheLoader<
|
||||
TestLoadParams,
|
||||
LocalMemoryTestEntityFields,
|
||||
string,
|
||||
'id',
|
||||
TestViewerContext,
|
||||
LocalMemoryTestEntity,
|
||||
LocalMemoryTestEntityPrivacyPolicy
|
||||
@@ -175,7 +177,6 @@ describe(LocalMemorySecondaryEntityCache, () => {
|
||||
const viewerContext = new TestViewerContext(createTestEntityCompanionProvider());
|
||||
|
||||
const createdEntity = await LocalMemoryTestEntity.creator(viewerContext)
|
||||
.enforcing()
|
||||
.setField('name', 'wat')
|
||||
.createAsync();
|
||||
|
||||
@@ -184,7 +185,7 @@ describe(LocalMemorySecondaryEntityCache, () => {
|
||||
localMemoryTestEntityConfiguration,
|
||||
GenericLocalMemoryCacher.createLRUCache<LocalMemoryTestEntityFields>({}),
|
||||
),
|
||||
LocalMemoryTestEntity.loader(viewerContext).withAuthorizationResults(),
|
||||
LocalMemoryTestEntity.loaderWithAuthorizationResults(viewerContext),
|
||||
);
|
||||
|
||||
const loadParams = { id: createdEntity.getID() };
|
||||
@@ -220,7 +221,7 @@ describe(LocalMemorySecondaryEntityCache, () => {
|
||||
localMemoryTestEntityConfiguration,
|
||||
GenericLocalMemoryCacher.createLRUCache<LocalMemoryTestEntityFields>({}),
|
||||
),
|
||||
LocalMemoryTestEntity.loader(viewerContext).withAuthorizationResults(),
|
||||
LocalMemoryTestEntity.loaderWithAuthorizationResults(viewerContext),
|
||||
);
|
||||
|
||||
const loadParams = { id: FAKE_ID };
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.build.json",
|
||||
"include": ["src"],
|
||||
}
|
||||
Loaded 100 of 267 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user