| 36 | import type { CollectionStateManager } from './state' |
| 37 | |
| 38 | export class CollectionMutationsManager< |
| 39 | TOutput extends object = Record<string, unknown>, |
| 40 | TKey extends string | number = string | number, |
| 41 | TUtils extends UtilsRecord = {}, |
| 42 | TSchema extends StandardSchemaV1 = StandardSchemaV1, |
| 43 | TInput extends object = TOutput, |
| 44 | > { |
| 45 | private lifecycle!: CollectionLifecycleManager<TOutput, TKey, TSchema, TInput> |
| 46 | private state!: CollectionStateManager<TOutput, TKey, TSchema, TInput> |
| 47 | private collection!: CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput> |
| 48 | private config!: CollectionConfig<TOutput, TKey, TSchema> |
| 49 | private id: string |
| 50 | |
| 51 | constructor(config: CollectionConfig<TOutput, TKey, TSchema>, id: string) { |
| 52 | this.id = id |
| 53 | this.config = config |
| 54 | } |
| 55 | |
| 56 | setDeps(deps: { |
| 57 | lifecycle: CollectionLifecycleManager<TOutput, TKey, TSchema, TInput> |
| 58 | state: CollectionStateManager<TOutput, TKey, TSchema, TInput> |
| 59 | collection: CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput> |
| 60 | }) { |
| 61 | this.lifecycle = deps.lifecycle |
| 62 | this.state = deps.state |
| 63 | this.collection = deps.collection |
| 64 | } |
| 65 | |
| 66 | private ensureStandardSchema(schema: unknown): StandardSchema<TOutput> { |
| 67 | // If the schema already implements the standard-schema interface, return it |
| 68 | if (schema && `~standard` in (schema as {})) { |
| 69 | return schema as StandardSchema<TOutput> |
| 70 | } |
| 71 | |
| 72 | throw new InvalidSchemaError() |
| 73 | } |
| 74 | |
| 75 | public validateData( |
| 76 | data: unknown, |
| 77 | type: `insert` | `update`, |
| 78 | key?: TKey, |
| 79 | ): TOutput | never { |
| 80 | if (!this.config.schema) return data as TOutput |
| 81 | |
| 82 | const standardSchema = this.ensureStandardSchema(this.config.schema) |
| 83 | |
| 84 | // For updates, we need to merge with the existing data before validation |
| 85 | if (type === `update` && key) { |
| 86 | // Get the existing data for this key |
| 87 | const existingData = this.state.get(key) |
| 88 | |
| 89 | if ( |
| 90 | existingData && |
| 91 | data && |
| 92 | typeof data === `object` && |
| 93 | typeof existingData === `object` |
| 94 | ) { |
| 95 | // Merge the update with the existing data |
nothing calls this directly
no test coverage detected