dev-master
9999999-devTransforms from one data form to another
MIT
Wallogit.com
2017 © Pedro Peláez
Transforms from one data form to another
This library is inspired by the REST APIS Best practices & the Fractal library., (*1)
Use Case: API Response Formatter, (*2)
** NOTE ** This is a work in Progress, (*3)
const express = require('app')
const datran = require('datran')
let app = express()
app.get('/user', async function(req, res) {
let resource = datran.item(await User.find(1))
let data = await datran.create(resource, new UserTransformer()).toObject()
res.status(200).json(data)
})
const { Transformer } = require('datran')
const UserTransformer = Transformer.create({
async transform(user) {
return {
id: user.get('_id'),
full_name: user.get('fullName')
}
}
})
or, (*4)
const { Transformer } = require('datran')
class UserTransformer extends Transformer {
async transform(user) {
return {
// formatted user data
}
}
}
availableIncludes array in the transformer and and optional defaultIncludes array.include{EmbeddedResource} in the transformer, which should call a separate Transformer.class CommentTransformer extends Transformer {
async transform(comment) {
return {
//formatted comments
}
}
}
class UserTransformer extends Transformer {
get availableIncludes() {
return ['comments']
}
get defaultIncludes() {
return ['comments']
}
async transform(user) {
return {
// formatted user data
}
}
includeComments(user) {
if (user.comments)
return this.collection(user.comments, new CommentTransformer())
}
}
When creating the datran resource, create an options object with a fields array, containing the resources to embed., (*5)
const opts = {
fields: ['comments']
}
app.get('/user', async function(req, res) {
const user = await User.find(1).populate('comments') //a user with a "comments" array
let resource = datran.item(user, opts)
let data = await datran.create(resource, new UserTransformer()).toObject()
res.status(200).json(data)
})
TODO Docs, (*6)
TODO Docs, (*7)
TODO Docs, (*8)
Transforms from one data form to another
MIT