A library for serializing and reading JSON API data in JavaScript. As of 2.0.0-beta.1 YAYSON respects JSON API Release candidate 4.
Install yayson by running:
$ npm install yayson --pre --save
A basic Presenter
can look like this:
{Presenter} = require('yayson')(adapter: 'default')
class ItemsPresenter extends Presenter
type: 'items'
item =
id: 5
name: 'First'
ItemsPresenter.render(item)
This would produce:
{
data: {
id: 5,
type: 'items',
attributes: {
id: 5,
name: 'First'
}
}
}
It also works with arrays, so if you send an array to render, "data" will be an array.
A bit more advanced example:
{Presenter} = require('yayson')(adapter: 'default')
class ItemsPresenter extends Presenter
type: 'items'
attributes: ->
attrs = super
attrs.start = moment.utc(attrs.start).toDate()
attrs
relationships: ->
event: EventsPresenter
ItemsPresenter.render(item)
In JavaScript this would be done as:
var Presenter = require('yayson')().Presenter;
var ItemsPresenter = function () { Presenter.call(this); }
ItemsPresenter.prototype = new Presenter();
ItemsPresenter.prototype.type = 'items'
ItemsPresenter.prototype.attributes = function() {
var attrs = Presenter.prototype.attributes.apply(this, arguments);
attrs.start = moment.utc(attrs.start).toDate();
return attrs;
}
ItemsPresenter.prototype.relationships = function() {
return {
event: EventsPresenter
}
}
ItemsPresenter.render(item)
By default it is set up to handle standard JS objects. You can also make it handle Sequalize.js models like this:
{Presenter} = require('yayson')(adapter: 'sequelize')
Take a look at the SequalizeAdapter if you want to extend YAYSON to your ORM. Pull requests are welccome :)
You can add metadata to the top level object.
ItemsPresenter.render(items, meta: count: 10)
This would produce:
{
meta: {
count: 10
}
data: {
id: 5,
type: 'items',
attributes: {
id: 5,
name: 'First'
}
}
}
You can use a Store
can like this:
{Store} = require('yayson')()
store = new Store()
adapter.get(path: '/events/' + id).then (data) ->
event = store.sync(data)
This will give you the parsed event with all its relationships.
Recommended way is to use it via webpack or similar build system wich lets you just require the package as usual.
If you just want to try it out, copy the file dist/yayson.js
to your project. Then simply include it:
<script src="./lib/yayson.js"></script>
Then you can var yayson = require('yayson')()
use the yayson.Presenter
and yayson.Store
as usual.
- Chrome
- Firefox
- Safari
- Safari iOS
- IE 9+
- Android