Services
Each resource
has an associated service that used by the store
or injected as needed. A resource service fetches or persists data using HTTP verbs: CREATE, PATCH, GET, and DELETE. The service named is the same name as the nouns used by your JSON API server. For example, request a post entity using GET /api/v1/posts
or GET /api/v1/posts/1
.
The application registers the service
instances as singleton objects with its container. Use a pluralized name for the entity which the service represents. An initializer for each resource provides a service
for your resource. The service extends an adapter with an injected serializer. The service is the mediator between the client's and server's representation of data.
The ember generate resource <entity>
command creates an initializer, resource, adapter, serializer, and service.
Resource Service
A resource
service is a combination of an adapter
, serializer
and cache
object. The service
is also injected into the resource
(model) objects.
Provide the caching plan for a service using a mixin, and customize as needed. To begin with, the resource
(model) prototype and the service-cache
mixin work together to provide a basic cache strategy for the resource.
Collaborators
Service objects are "evented" to provide close to real-time updates:
- When an
attr
isset
and the value has changed, then the resource instance triggers anattributeChanged
event. The resource's service singleton object may listen for the event and handle it with a call toupdateResource
via the resource's adapter. - The resource adapter's
updateResource
method sends a PATCH request. The request body includes changed attributes. The serializer'sserializeChanged
method provides the data for the PATCH request.
You may want to buffer changes on the resource when passing it into a component by using ember-buffered-proxy. Alternatively, re-define the resource's adapter prototype. Change the initEvents
method to return a no-op function instead of observing the attributeChanged
event.
Service Example
The Service prototype below extends the Post adapter and mixes in the default cache mixin:
import Adapter from '../adapters/post';
import ServiceCache from 'ember-jsonapi-resources/mixins/service-cache';
Adapter.reopenClass({ isServiceFactory: true });
export default Adapter.extend(ServiceCache);