| repo | andersondanilo/jsonapi-fractal |
|---|---|
| url | https://github.com/andersondanilo/jsonapi-fractal |
| homepage | |
| starredAt | 2025-01-24T00:02:01Z |
| createdAt | 2020-04-08T22:52:34Z |
| updatedAt | 2025-02-15T17:28:48Z |
| language | TypeScript |
| license | MIT |
| branch | master |
| stars | 58 |
| isPublic | true |
| isTemplate | false |
| isArchived | false |
| isFork | false |
| hasReadMe | true |
| refreshedAt | 2025-02-25T19:51:10.745Z |
| description | JSON:API Serializer inspired by Fractal (PHP) |
| tags |
JSON:API Serializer inspired by Fractal (PHP)
yarn add jsonapi-fractal
OR
npm install jsonapi-fractal --save
// examples/simple-serialize.js
const { serialize, CaseType } = require('jsonapi-fractal')
const entity = {
id: 1,
firstName: 'Joe',
lastName: 'Doe',
address: {
id: 1,
},
images: [{ id: 1 }, { id: 2 }],
}
const serialized = serialize(entity, 'users', {
relationships: ['address', 'images'],
changeCase: CaseType.kebabCase,
})
console.log(JSON.stringify(serialized))
/**
* OUTPUT:
*
* {
* "data": {
* "id": 1,
* "type": "users",
* "attributes": {
* "first-name": "Joe",
* "last-name": "Doe"
* },
* "relationships": {
* "address": {
* "data": {
* "id": 1,
* "type": "address"
* }
* },
* "images": {
* "data": [
* {
* "id": 1,
* "type": "images"
* },
* {
* "id": 2,
* "type": "images"
* }
* ]
* }
* }
* }
* }
*/// examples/deserialize.js
const { deserialize, CaseType } = require('jsonapi-fractal')
const serializedData = {
data: {
id: 'myuserid',
type: 'users',
attributes: {
name: 'Joe',
'last-name': 'Doe',
},
},
}
const entity = deserialize(serializedData, { changeCase: CaseType.camelCase })
console.log(JSON.stringify(entity))
/**
* OUTPUT:
*
* {
* "id": "myuserid",
* "name": "Joe",
* "lastName": "Doe"
* }
*/// examples/serialize-with-transformers.js
const { Transformer, DefaultTransformer, transform, whitelist } = require('jsonapi-fractal')
class UserTransformer extends Transformer {
constructor() {
super()
this.type = 'users'
this.relationships = {
images: this.images,
}
}
transform(user, options) {
return whitelist(user, ['_id', 'firstName', 'lastName'])
}
images(user, options) {
return transform()
.withInput(user.images)
.withTransformer(new DefaultTransformer('images'))
.withIncluded(true)
.toContext()
}
}
const user = {
_id: 1,
firstName: 'Joe',
lastName: 'Doe',
images: [{ _id: 5, url: 'http://' }],
}
const serialized = transform()
.withInput(user)
.withTransformer(new UserTransformer())
.withOptions({ idKey: '_id' })
.serialize()
console.log(JSON.stringify(serialized))
/**
* OUTPUT:
*
* {
* "data": {
* "id": 1,
* "type": "users",
* "attributes": {
* "firstName": "Joe",
* "lastName": "Doe"
* },
* "relationships": {
* "images": {
* "data": [
* {
* "id": 5,
* "type": "images"
* }
* ]
* }
* }
* },
* "included": [
* {
* "id": 5,
* "type": "images",
* "attributes": {
* "url": "http://"
* }
* }
* ]
* }
*/