npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

sails-hook-cerealize

v1.0.5

Published

A serializer similar in syntax use to rails active model serializers

Downloads

13

Readme

Sails-Hook-Cerealizer

Provides json serialization for nested records with similar syntax to the ActiveModelSerializers

Installation

npm install --save sails-hook-cerealize

The Cerealizer

You will need two services. One that news up a Cerealize on call (since they are being globally namespaced anyways). The Second will be a Cerealizer, which will be used to set your individual serializer configurations.

I have provided a view of how the models for the example are set up for relational data purposes only. Cerealize is model agnostic, and only cares about the records you pass it, and that there is a Cerealizer by the name you provide to its configuration.

Cerealize

var Cerealize = require('sails-hook-cerealize/Cerealize.js');

module.exports = function(records, config)  { return (new Cerealize(records, config)); }

Cerealizer

var Cerealizer = require('sails-hook-cerealize/Cerealizer.js');

module.exports = Cerealizer;

api/models:

Character

module.exports =

  attributes: {

    name:
      type: 'string'

    is_public: 
      type: 'boolean'
      defaultsTo: () -> "false"

    experience:
      type: 'integer'
      defaultsTo: () -> 0

    base_ability_score:
      model: 'ability_score'
      dominant: true

    ability_score_modifications:
      collection: 'ability_score'
      dominant: true

    level:
      type: 'integer'
      defaultsTo:() -> 1
    #one race to one character
    race: 
      model: 'race'
      dominant: true 
    # one character to many klasses
    primary_class:
      model: 'klass'
      # defaultsTo:() -> some_filler_class
    # one character to many klasses
    secondary_classes:
      collection: 'klass'
      via: 'characters'
      dominant: true
    # one player to many characters
    created_by:
      model: 'user'

  },

  beforeCreate: (char, cb) ->
    if !char.base_ability_score
      Ability_score.create().exec((err, created) ->
        return cb(err) if err 
        char.base_ability_score = created.id
        cb()
      )
    else
      cb()

Race

module.exports =

  attributes: {

    name:
      type: "string"

    description:
      type: "string"

    characters:
      collection: 'character'
      via: 'race'
  }

Klass

module.exports =

  attributes: {

    name:
      type: 'string'

    description:
      type: 'string'

    level:
      type: 'integer'
      defaultsTo: () -> 1

    hit_dice_type:
      type: 'integer'

    hit_dice: 
      type: 'integer'

    characters:
      collection: 'character'
      via: 'secondary_classes'

  }

Ability Score

module.exports =

  attributes: {

    strength:
      type: 'integer'
      defaultsTo:() -> 0

    dexterity:
      type: 'integer'
      defaultsTo:() -> 0

    constitution: 
      type: 'integer'
      defaultsTo:() -> 0

    intelligence:
      type: 'integer'
      defaultsTo:() -> 0

    wisdom: 
      type: 'integer'
      defaultsTo:() -> 0

    charisma:
      type: 'integer'
      defaultsTo:() -> 0

  }

api/serializers

Serializer Naming Convention

  • CamelCasedSerializer.(js/coffee)

Serializers should export a new Cerealizer([params]) with an array of objects as its defining parameters. The paramater objects should contain a single attribute named for its relationship to the passed in records.

attributes

value should be an array of strings which keys the serialized output will have. Note that these must be either attributes already on the passed in record, or a self defined attribute listed in the serializer objects.

has_one

value should be an object with an attribute named for the records attribute name it will serialize, and an attribute value that is a config object, with an attribute named 'serializer' and a value that is a string of the name of the serializer to be called. examples follow.

has_many

value should be an object with an attribute named for the records attribute name it will serialize, and an attribute value that is a config object, with an attribute named 'each_serializer' and a value that is a string of the name of the serializer to be called. examples follow. nested has_manys that have has_manys of their initial json, are currently broken

user defined functions

value may be an attribute named anything other than an attribute already on the record. The attribute value will be a function being passed in a record as the first argument. The return value from the function will be set to the value of attribute in the final serialized version. Returning of promises is currently broken.

future implentation** mimicked attribute functions

value may be an attribute named for an attribute already on the record. The attribute value should be a function being passed in the records.attribute as the first argument, the record as the second argument, and the user as the third argument The return value would become the attributes value on the final serialized version, would be able to return promises.

CharacterSerializer

CharacterSerializer = new Cerealizer([
  { attributes: ['name', 'race', 'standard_func', 'secondary_classes', 'primary_class', 'base_ability_score'] },
  { has_many: { secondary_classes: { each_serializer: 'Klass' } } },
  { has_one: { primary_class: { serializer: 'Klass' } } },
  { has_one: { race: { serializer: 'Race' } } },
  { has_one: { base_ability_score: { serializer: 'BaseAbilityScore' } } },

  { standard_func: (record, user) -> return record.id + '-' + record.name }

]);

module.exports = CharacterSerializer

RaceSerializer

RaceSerializer = new Cerealizer([
  { attributes: ['name', 'description'] }
  # -> nested cross relations not supported yet { has_many: { characters: { each_serializer: 'Character' } } }
]);

module.exports = RaceSerializer

KlassSerializer

KlassSerializer = new Cerealizer([
  { attributes: ['name', 'description', 'hit_dice_type', 'hit_dice', 'refill'] },
  { refill: (record) -> return "#{record.hit_dice}D#{record.hit_dice_type}" }
]);

module.exports = KlassSerializer

BaseAbilityScoreSerializer

BaseAbilityScore = new Cerealizer([
  { attributes: ['charisma', 'constitution', 'dexterity', 'intelligence', 'strength', 'wisdom'] }
]);

module.exports = BaseAbilityScore

api/controllers

controller conventions

provided your service is named Cerealize like mine is, you may call your serializer in the controller as below. You may notice, Cerealize returns a bluebird promise, so catch that return, and serve it up as you please. I have a packaging service here that checks for errors, and either returns the errors or the json after each catch.

module.exports = {
  index: (req, res) ->
    Character.find()
    .populate('created_by')
    .populate('primary_class')
    .populate('secondary_classes')
    .populate('race')
    .populate('base_ability_score')
    .exec((err, characters) ->
      race_ids = _.map(characters, (c) -> c.race.id)
      Race.find(race_ids)
      .populate('characters')
      .exec((err, races) ->
        characters = _.map(characters, (c) -> c.race = _.filter(races, { id: c.race.id })[0]; return c;)
        Cerealize(characters, { each_serializer: 'Character' }).then (ret) ->
          return Packager.chego(req, res, err, ret[Object.keys(ret)[0]])
      )
    )
}

The above serialized data would appear as an object with an attribute equal to the given serializer name with an attribuite value of either an object or array of objects, which each may or may not be serialized, depending on your configuration:

  { character: 
   [ { id: 1,
       name: 'BrothamireTheron',
       race: [Object],
       standard_func: '1-BrothamireTheron',
       promise_func: null,
       secondary_classes: [Object],
       primary_class: [Object],
       base_ability_score: [Object] 
     }, { 
      id: 2,
      name: 'Hodoor',
      race: [Object],
      standard_func: '2-Hodoor',
      promise_func: null,
      secondary_classes: [Object],
      primary_class: [Object],
      base_ability_score: [Object]
     }, {
      id: 3,
      name: 'Hodoor',
      race: [Object],
      standard_func: '3-Hodoor',
      promise_func: null,
      secondary_classes: [Object],
      primary_class: [Object],
      base_ability_score: [Object]
     }, {
      id: 4,
      name: 'scoob',
      race: [Object],
      standard_func: '4-scoob',
      promise_func: null,
      secondary_classes: [Object],
      primary_class: [Object],
      base_ability_score: [Object]
     } ]
  }