MCPcopy
hub / github.com/directus/directus / createField

Method createField

api/src/services/fields.ts:359–501  ·  view source on GitHub ↗
(
		collection: string,
		field: Partial<Field> & { field: string; type: Type | null },
		table?: Knex.CreateTableBuilder, // allows collection creation to
		opts?: FieldMutationOptions,
	)

Source from the content-addressed store, hash-verified

357 }
358
359 async createField(
360 collection: string,
361 field: Partial<Field> & { field: string; type: Type | null },
362 table?: Knex.CreateTableBuilder, // allows collection creation to
363 opts?: FieldMutationOptions,
364 ): Promise<void> {
365 if (this.accountability && this.accountability.admin !== true) {
366 throw new ForbiddenError();
367 }
368
369 const runPostColumnChange = await this.helpers.schema.preColumnChange();
370 const nestedActionEvents: ActionEventParams[] = [];
371
372 try {
373 const exists =
374 field.field in this.schema.collections[collection]!.fields ||
375 isNil(
376 await this.knex.select('id').from('directus_fields').where({ collection, field: field.field }).first(),
377 ) === false;
378
379 // Check if field already exists, either as a column, or as a row in directus_fields
380 if (exists) {
381 throw new InvalidPayloadError({
382 reason: `Field "${field.field}" already exists in collection "${collection}"`,
383 });
384 }
385
386 // Add flag for specific database type overrides
387 const flagToAdd = this.helpers.date.fieldFlagForField(field.type);
388
389 if (flagToAdd) {
390 addFieldFlag(field, flagToAdd);
391 }
392
393 let hookAdjustedField = field;
394 const attemptConcurrentIndex = Boolean(opts?.attemptConcurrentIndex);
395
396 await transaction(this.knex, async (trx) => {
397 const itemsService = new ItemsService('directus_fields', {
398 knex: trx,
399 accountability: this.accountability,
400 schema: this.schema,
401 });
402
403 hookAdjustedField =
404 opts?.emitEvents !== false
405 ? await emitter.emitFilter(
406 `fields.create`,
407 field,
408 {
409 collection: collection,
410 },
411 {
412 database: trx,
413 schema: this.schema,
414 accountability: this.accountability,
415 },
416 )

Callers 4

generateTranslationsFunction · 0.95
applyDiffFunction · 0.95
handlerFunction · 0.95

Calls 15

addColumnToTableMethod · 0.95
createOneMethod · 0.95
addColumnIndexMethod · 0.95
addFieldFlagFunction · 0.90
transactionFunction · 0.85
getDatabaseFunction · 0.85
shouldClearCacheFunction · 0.85
clearSystemCacheFunction · 0.85
getSchemaFunction · 0.85
preColumnChangeMethod · 0.80
fromMethod · 0.80
emitFilterMethod · 0.80

Tested by

no test coverage detected