A library that provides custom JSON notation for the find method of TypeORM
npm install serafim
npm install --save serafim
`
$3
Given the following entities and relationships:
`jsx
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@Column()
password: string;
@OneToOne(() => Person)
person: Person;
@OneToOne(() => ProfilePicture)
profilePicture: ProfilePicture;
}
`
`jsx
@Entity()
export class ProfilePicture {
@PrimaryGeneratedColumn()
id: number;
@Column()
path: string;
}
`
`jsx
@Entity()
export class Person {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
surname: string;
@OneToOne(() => Address)
address: Address;
}
`
`jsx
@Entity()
export class Address {
@PrimaryGeneratedColumn()
id: number;
@Column()
address: string;
@Column()
zip: number;
}
`
To extract custom information, you have to write custom queries, and there are two ways to do that in TypeORM. The first is to write queries using raw SQL, which uses the query method. The second way is to use the find method and specify the params. In both ways one would have to write an API, either to write custom raw SQL, either to customize the params. This package uses the latter, by translating JSON into meaningful params.
Only using TypeORM:
`jsx
//frontend
const search = {
relations: {
person: {
address: true
},
profilePicture: true
},
where: [
{
person: {
address: {
state: "NY"
}
}
},
{
profilePicture: {
id: 1
}
}
],
order: {
person: {
address: {
state: "ASC"
}
}
}
}
//backend
userRepository.find({
relations: search.relations,
where: search.where,
order: search.order,
})
`
Using Serafim:
`jsx
//frontend
const search: Search = {
where: [
{
field: "person.address.state",
searchTerm: "NY",
},
{
field: "profilePicture.id",
searchTerm: 1
}
],
order: {
field: "person.address.state",
sortOrder: "ASC",
}
};
//backend
userRepository.find({
relations: getRelations(search.where), // search.where, not search.relations
where: getWhere(search.where),
order: getOrder(search.order),
})
``