Take control

of your models

Dapeng Li

Models

  • Represents domain concepts
  • Data + Behaviour

Is JSON enough?

  • Couples with use case
  • Couples with backend
  • Encourages arbitrary mutation

Transformation

{
  channelId: 123,
  adSet: {
    budget: {
      type: 'foo'
    }
  },
  created: {
    date: "2016-03-15T13:10:16Z"
  }
  //adPixels: []
}
{
  adChannelId: 123,
  adSetBudgetType: 'foo',
  createdDate: "2016-03-15T13:10:16.000Z",
  adPixels: []
}
  • Alias
  • Path look up
  • Transform
  • Set default value

Transform with apiSmith

// add reference to apiSmith
// retrieve backendModel

function toDateStringWithUTC(date) {
  return new Date(date).toJSON();
}

const TRANSFORMATION = {
  adChannelId: 'channelId',
  adSetBudgetType: {
    from: ['adSet', 'budget', 'type']
  },
  createdDate: {
    from: ['created', 'date'],
    transformer: toDateStringWithUTC
  },
  adPixels: {
    from: 'adPixels',
    default: []
  }
};

const transformModel = apiSmith.smash(TRANSFORMATION);

const transformed = transformModel(backendModel);

Benefits

  • Decoupling
  • Schema
  • Control

APISmith (Ruby)

class MyResponse < APISmith::Smash
  property :full_name, :from => :fullName
  property :value_percentage, :transformer => :to_f
  property :short_name
  property :created, :transformer => lambda { |v| Date.parse(v) }
end

response = MyResponse.new({
  :fullName         => "Bob Smith",
  :value_percentage => "10.5",
  :short_name       => 'Bob',
  :created          => '2010-12-28'
})

p response.short_name # => "Bob"
p response.full_name # => "Bob Smith"
p response.value_percentage # => 10.5
p response.created.class # => Date

apiSmith in HTML-Client

 

  • apiSmith.service.js
  • apiSmith.service.spec.es6
  • promotion-publication.factory.js

Thank you

take_control_models

By Dapeng Li

take_control_models

  • 643