Vai al contenuto principale

Separazione della Definizione dell'Entità

Traduzione Beta Non Ufficiale

Questa pagina è stata tradotta da PageTurner AI (beta). Non ufficialmente approvata dal progetto. Hai trovato un errore? Segnala problema →

Definizione degli Schemi

Puoi definire un'entità e le sue colonne direttamente nel modello utilizzando i decoratori. Tuttavia, alcuni preferiscono definire un'entità e le sue colonne in file separati chiamati "schemi di entità" in TypeORM.

Esempio di definizione semplice:

import { EntitySchema } from "typeorm"

export const CategoryEntity = new EntitySchema({
name: "category",
columns: {
id: {
type: Number,
primary: true,
generated: true,
},
name: {
type: String,
},
},
})

Esempio con relazioni:

import { EntitySchema } from "typeorm"

export const PostEntity = new EntitySchema({
name: "post",
columns: {
id: {
type: Number,
primary: true,
generated: true,
},
title: {
type: String,
},
text: {
type: String,
},
},
relations: {
categories: {
type: "many-to-many",
target: "category", // CategoryEntity
},
},
})

Esempio complesso:

import { EntitySchema } from "typeorm"

export const PersonSchema = new EntitySchema({
name: "person",
columns: {
id: {
primary: true,
type: "int",
generated: "increment",
},
firstName: {
type: String,
length: 30,
},
lastName: {
type: String,
length: 50,
nullable: false,
},
age: {
type: Number,
nullable: false,
},
countryCode: {
type: String,
length: 2,
foreignKey: {
target: "countries", // CountryEntity
inverseSide: "code",
},
},
cityId: {
type: Number,
foreignKey: {
target: "cities", // CityEntity
},
},
},
checks: [
{ expression: `"firstName" <> 'John' AND "lastName" <> 'Doe'` },
{ expression: `"age" > 18` },
],
indices: [
{
name: "IDX_TEST",
unique: true,
columns: ["firstName", "lastName"],
},
],
uniques: [
{
name: "UNIQUE_TEST",
columns: ["firstName", "lastName"],
},
],
foreignKeys: [
{
target: "cities", // CityEntity
columnNames: ["cityId", "countryCode"],
referencedColumnNames: ["id", "countryCode"],
},
],
})

Per rendere la tua entità type-safe, puoi definire un modello e specificarlo nella definizione dello schema:

import { EntitySchema } from "typeorm"

export interface Category {
id: number
name: string
}

export const CategoryEntity = new EntitySchema<Category>({
name: "category",
columns: {
id: {
type: Number,
primary: true,
generated: true,
},
name: {
type: String,
},
},
})

Estensione degli Schemi

Con l'approccio Decorator è semplice extend colonne di base in una classe astratta e poi estenderla. Ad esempio, le colonne id, createdAt e updatedAt potrebbero essere definite in una BaseEntity. Per dettagli, vedi la documentazione su ereditarietà a tabella concreta.

Con l'approccio EntitySchema, questo non è possibile. Tuttavia, puoi sfruttare Spread Operator (...) a tuo vantaggio.

Riconsidera l'esempio Category precedente. Potresti voler extract le descrizioni delle colonne base e riutilizzarle in altri schemi. Puoi farlo così:

import { EntitySchemaColumnOptions } from "typeorm"

export const BaseColumnSchemaPart = {
id: {
type: Number,
primary: true,
generated: true,
} as EntitySchemaColumnOptions,
createdAt: {
name: "created_at",
type: "timestamp with time zone",
createDate: true,
} as EntitySchemaColumnOptions,
updatedAt: {
name: "updated_at",
type: "timestamp with time zone",
updateDate: true,
} as EntitySchemaColumnOptions,
}

Ora puoi usare BaseColumnSchemaPart in altri modelli di schema, in questo modo:

export const CategoryEntity = new EntitySchema<Category>({
name: "category",
columns: {
...BaseColumnSchemaPart,
// the CategoryEntity now has the defined id, createdAt, updatedAt columns!
// in addition, the following NEW fields are defined
name: {
type: String,
},
},
})

Puoi usare entità incorporate nei modelli di schema, così:

export interface Name {
first: string
last: string
}

export const NameEntitySchema = new EntitySchema<Name>({
name: "name",
columns: {
first: {
type: "varchar",
},
last: {
type: "varchar",
},
},
})

export interface User {
id: string
name: Name
isActive: boolean
}

export const UserEntitySchema = new EntitySchema<User>({
name: "user",
columns: {
id: {
primary: true,
generated: "uuid",
type: "uuid",
},
isActive: {
type: "boolean",
},
},
embeddeds: {
name: {
schema: NameEntitySchema,
prefix: "name_",
},
},
})

Assicurati di aggiungere le colonne extended anche all'interfaccia Category (ad esempio tramite export interface Category extend BaseEntity).

Ereditarietà a Tabella Singola

Per usare l'Ereditarietà a Tabella Singola:

  1. Aggiungi l'opzione inheritance allo schema della classe genitore, specificando il pattern di ereditarietà ("STI") e la colonna discriminatore, che memorizzerà il nome della classe figlia in ogni riga

  2. Imposta l'opzione type: "entity-child" per tutti gli schemi delle classi figlie, estendendo le colonne della classe genitore usando la sintassi dell'operatore spread descritta sopra

// entity.ts

export abstract class Base {
id!: number
type!: string
createdAt!: Date
updatedAt!: Date
}

export class A extends Base {
constructor(public a: boolean) {
super()
}
}

export class B extends Base {
constructor(public b: number) {
super()
}
}

export class C extends Base {
constructor(public c: string) {
super()
}
}
// schema.ts

const BaseSchema = new EntitySchema<Base>({
target: Base,
name: "Base",
columns: {
id: {
type: Number,
primary: true,
generated: "increment",
},
type: {
type: String,
},
createdAt: {
type: Date,
createDate: true,
},
updatedAt: {
type: Date,
updateDate: true,
},
},
// NEW: Inheritance options
inheritance: {
pattern: "STI",
column: "type",
},
})

const ASchema = new EntitySchema<A>({
target: A,
name: "A",
type: "entity-child",
// When saving instances of 'A', the "type" column will have the value
// specified on the 'discriminatorValue' property
discriminatorValue: "my-custom-discriminator-value-for-A",
columns: {
...BaseSchema.options.columns,
a: {
type: Boolean,
},
},
})

const BSchema = new EntitySchema<B>({
target: B,
name: "B",
type: "entity-child",
discriminatorValue: undefined, // Defaults to the class name (e.g. "B")
columns: {
...BaseSchema.options.columns,
b: {
type: Number,
},
},
})

const CSchema = new EntitySchema<C>({
target: C,
name: "C",
type: "entity-child",
discriminatorValue: "my-custom-discriminator-value-for-C",
columns: {
...BaseSchema.options.columns,
c: {
type: String,
},
},
})

Utilizzo degli Schemi per Query/Inserimento Dati

Naturalmente, puoi usare gli schemi definiti nei repository o nell'entity manager esattamente come faresti con i decoratori. Considera l'esempio Category definito precedentemente (con la sua Interface e lo schema CategoryEntity) per ottenere dati o manipolare il database.

// request data
const categoryRepository = dataSource.getRepository<Category>(CategoryEntity)
const category = await categoryRepository.findOneBy({
id: 1,
}) // category is properly typed!

// insert a new category into the database
const categoryDTO = {
// note that the ID is autogenerated; see the schema above
name: "new category",
}
const newCategory = await categoryRepository.save(categoryDTO)