|
| 1 | +import { DMMF } from '@prisma/generator-helper'; |
| 2 | + |
| 3 | +export function generateManyToManyTables(models: DMMF.Model[]): string[] { |
| 4 | + const manyToManyFields = filterManyToManyRelationFields(models); |
| 5 | + if (manyToManyFields.length === 0) { |
| 6 | + return []; |
| 7 | + } |
| 8 | + |
| 9 | + return generateTables(manyToManyFields, models); |
| 10 | +} |
| 11 | + |
| 12 | +function generateTables( |
| 13 | + manyToManyFields: DMMF.Field[], |
| 14 | + models: DMMF.Model[], |
| 15 | + manyToManyTables: string[] = [] |
| 16 | +): string[] { |
| 17 | + const manyFirst = manyToManyFields.shift(); |
| 18 | + if (!manyFirst) { |
| 19 | + return manyToManyTables; |
| 20 | + } |
| 21 | + |
| 22 | + const manySecond = manyToManyFields.find( |
| 23 | + (field) => field.relationName === manyFirst.relationName |
| 24 | + )!; |
| 25 | + |
| 26 | + manyToManyTables.push( |
| 27 | + `Table ${manyFirst?.relationName} {\n` + |
| 28 | + `${generateJoinFields([manyFirst, manySecond], models)}` + |
| 29 | + '\n}' |
| 30 | + ); |
| 31 | + |
| 32 | + return generateTables( |
| 33 | + manyToManyFields.filter( |
| 34 | + (field) => field.relationName !== manyFirst.relationName |
| 35 | + ), |
| 36 | + models, |
| 37 | + manyToManyTables |
| 38 | + ); |
| 39 | +} |
| 40 | + |
| 41 | +function generateJoinFields(field: DMMF.Field[], models: DMMF.Model[]): string { |
| 42 | + return field.map((field) => joinField(field, models)).join('\n'); |
| 43 | +} |
| 44 | + |
| 45 | +function joinField(field: DMMF.Field, models: DMMF.Model[]): string { |
| 46 | + return ` ${field.type.toLowerCase()}Id ${getJoinIdType( |
| 47 | + field, |
| 48 | + models |
| 49 | + )} [ref: > ${field.type}.${field.relationToFields![0]}]`; |
| 50 | +} |
| 51 | + |
| 52 | +function getJoinIdType(joinField: DMMF.Field, models: DMMF.Model[]): string { |
| 53 | + const joinIdField = models |
| 54 | + .filter((model) => model.name === joinField.type) |
| 55 | + .map( |
| 56 | + (model) => |
| 57 | + model.fields.find( |
| 58 | + (field) => field.name === joinField.relationToFields![0] |
| 59 | + )! |
| 60 | + )[0]; |
| 61 | + |
| 62 | + return joinIdField.type; |
| 63 | +} |
| 64 | + |
| 65 | +function filterManyToManyRelationFields(models: DMMF.Model[]): DMMF.Field[] { |
| 66 | + return models |
| 67 | + .map((model) => |
| 68 | + model.fields |
| 69 | + .filter( |
| 70 | + (field) => |
| 71 | + field.relationName && |
| 72 | + field.isList && |
| 73 | + field.relationFromFields?.length === 0 && |
| 74 | + field.relationToFields?.length |
| 75 | + ) |
| 76 | + .map((field) => field) |
| 77 | + ) |
| 78 | + .flat(); |
| 79 | +} |
0 commit comments