A method to fetch resources that are not included in a document has to be provided by the user of Grivet by implementing the Context interface. This makes the library more easily adaptable to various frameworks and different HTTP client libraries. The Context interface looks like this:
Basically, a Context implementation just has to provide a getDocument method that returns a Promise of a JsonApiDocument when given a URL. Just one thing to keep in mind: As per the specification, a request to a JSON:API server has to include the Accept header with the value application/vnd.api+json.
In the above example, an Angular http client is used with its Observable converted to a Promise. The Accept header is set in the constructor so that all subsequent requests use this value.
A Context implementation does not have to perform any HTTP requests. It can also just return responses from any other source, such as pre-defined responses for testing purposes. The following Context takes a TestApi object and just returns a resolved Promise filled with data taken from the TestApi object keyed by pathname:
classTestContextimplementsJsonApi.Context { constructor(privatereadonlytestApi: TestApi) {} getDocument(url: URL): Promise<Spec.JsonApiDocument> { if (!(url.pathnameinthis.testApi)) { returnPromise.reject(`The path "${url.pathname}" was not found in testApi`); } returnPromise.resolve(this.testApi[url.pathname]); } }
You can then define a test API and use it in your unit tests:
Implement this interface to define how a JsonApiDocument (the JSON:API raw data) is fetched from a given URL.
Implementing the
ContextinterfaceA method to fetch resources that are not included in a document has to be provided by the user of Grivet by implementing the
Contextinterface. This makes the library more easily adaptable to various frameworks and different HTTP client libraries. TheContextinterface looks like this:Basically, a
Contextimplementation just has to provide agetDocumentmethod that returns aPromiseof aJsonApiDocumentwhen given aURL. Just one thing to keep in mind: As per the specification, a request to a JSON:API server has to include theAcceptheader with the valueapplication/vnd.api+json.Example Angular http context
An implementation based on the Angular http client could look like this:
In the above example, an Angular http client is used with its
Observableconverted to aPromise. TheAcceptheader is set in the constructor so that all subsequent requests use this value.Example Node http context using axios
Example context for testing
A
Contextimplementation does not have to perform any HTTP requests. It can also just return responses from any other source, such as pre-defined responses for testing purposes. The followingContexttakes aTestApiobject and just returns a resolvedPromisefilled with data taken from theTestApiobject keyed bypathname:You can then define a test API and use it in your unit tests: