(
kysely: AnyKysely,
model: string,
data: any,
fromRelation?: FromRelationContext,
creatingForDelegate = false,
returnFields?: readonly string[],
)
| 378 | } |
| 379 | |
| 380 | protected async create( |
| 381 | kysely: AnyKysely, |
| 382 | model: string, |
| 383 | data: any, |
| 384 | fromRelation?: FromRelationContext, |
| 385 | creatingForDelegate = false, |
| 386 | returnFields?: readonly string[], |
| 387 | ): Promise<unknown> { |
| 388 | const modelDef = this.requireModel(model); |
| 389 | |
| 390 | // additional validations |
| 391 | if (modelDef.isDelegate && !creatingForDelegate) { |
| 392 | throw createNotSupportedError(`Model "${model}" is a delegate and cannot be created directly.`); |
| 393 | } |
| 394 | |
| 395 | let createFields: any = {}; |
| 396 | let updateParent: ((entity: any) => void) | undefined = undefined; |
| 397 | |
| 398 | let m2m: ReturnType<typeof getManyToManyRelation> = undefined; |
| 399 | |
| 400 | if (fromRelation) { |
| 401 | m2m = getManyToManyRelation(this.schema, fromRelation.model, fromRelation.field); |
| 402 | if (!m2m) { |
| 403 | // many-to-many relations are handled after create |
| 404 | const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs( |
| 405 | this.schema, |
| 406 | fromRelation?.model ?? '', |
| 407 | fromRelation?.field ?? '', |
| 408 | ); |
| 409 | |
| 410 | if (!ownedByModel) { |
| 411 | // assign fks from parent |
| 412 | const parentFkFields = await this.buildFkAssignments( |
| 413 | kysely, |
| 414 | fromRelation.model, |
| 415 | fromRelation.field, |
| 416 | fromRelation.ids, |
| 417 | ); |
| 418 | Object.assign(createFields, parentFkFields); |
| 419 | } else { |
| 420 | // record parent fk update after entity is created |
| 421 | updateParent = (entity) => { |
| 422 | for (const { fk, pk } of keyPairs) { |
| 423 | fromRelation.parentUpdates[fk] = entity[pk]; |
| 424 | } |
| 425 | }; |
| 426 | } |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | // process the create and handle relations |
| 431 | const postCreateRelations: Record<string, object> = {}; |
| 432 | for (const [field, value] of Object.entries(data)) { |
| 433 | const fieldDef = this.requireField(model, field); |
| 434 | if (isScalarField(this.schema, model, field) || isForeignKeyField(this.schema, model, field)) { |
| 435 | if ( |
| 436 | fieldDef.array && |
| 437 | value && |
nothing calls this directly
no test coverage detected