Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/arfedulov/typeorm-jsonapi-serializer
Jsonapi (de)serialization for typeorm
https://github.com/arfedulov/typeorm-jsonapi-serializer
Last synced: 3 months ago
JSON representation
Jsonapi (de)serialization for typeorm
- Host: GitHub
- URL: https://github.com/arfedulov/typeorm-jsonapi-serializer
- Owner: arfedulov
- Created: 2019-11-03T12:15:23.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2023-01-05T03:02:17.000Z (about 2 years ago)
- Last Synced: 2024-10-06T02:41:28.209Z (3 months ago)
- Language: TypeScript
- Size: 1.05 MB
- Stars: 8
- Watchers: 4
- Forks: 1
- Open Issues: 15
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# typeorm-jsonapi-serializer
Provides (de)serialization of jsonapi data for typeorm.
:warning: Deserialization of many-to-many relationships implemented via
typeorm liking entity is not supported yet. You will get an error
if you try to deserialize such relationships. Skip such relationsips
using `@Skip` decorator or use typeorm's `@ManyToMany` decorator ( many-to-many
relationships implemented with this decorator should be deserialized fine ).## Usage
### serialization
```ts
import { Serializable, Skip, Serializer } from '@arfedulov/typeorm-jsonapi-serializer';@Entity()
@Serializable('zoos')
class Zoo {
@PrimaryGeneratedColumn()
id!: number;@OneToMany((type) => Animal, (animal) => animal.zoo)
animals?: Promise;
}@Entity()
@Serializable('animals')
class Animal {
@PrimaryGeneratedColumn()
id!: number;@Column()
name!: string;@Column()
@Skip
secretName!: string;@ManyToOne((type) => Zoo, (zoo) => zoo.animals)
zoo!: Promise;
}const zoo = new Zoo();
zoo.id = 0;const animal = new Animal();
animal.id = 1;
animal.zoo = zoo;
animal.name = 'bear';
animal.secretName = '^(-.-)^';const data = Serializer()(animal);
console.log(data);
/*
{
"id": "1",
"type": "animals",
"attributes": {
"name": "bear"
},
"relationships": {
"zoo": {
"data": {
"id": "0",
"type": "zoos"
}
}
}
}*/
```### deserialization
```ts
import { Deserializer } from '@arfedulov/typeorm-jsonapi-serializer';
import { Animal } from './entity/Animal';
import assert from 'assert';const data = {
id: '1',
type: 'animals',
attributes: {
name: 'bear'
},
relationships: {
zoo: {
data: {
id: '0',
type: 'zoos'
}
}
}
};const EXPECT = new Animal();
EXPECT.id = 1;
EXPECT.name = 'bear';
EXPECT.zoo = Promise.resolve(new Zoo(0/*id*/))
const animal = Deserializer()(data);assert.deepStrictEqual(animal, EXPECT);
/* OK */```
### deserializing relationshipsSee [Deserializer.test.ts](https://github.com/arfedulov/typeorm-jsonapi-serializer/blob/master/src/Deserializer/__tests__/Deserializer.test.ts) and [deserializeRelation.test.ts](https://github.com/arfedulov/typeorm-jsonapi-serializer/blob/master/src/Deserializer/__tests__/deserializeRelation.test.ts).