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
Context
interfaceA 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. TheContext
interface looks like this:Basically, a
Context
implementation just has to provide agetDocument
method that returns aPromise
of aJsonApiDocument
when given aURL
. Just one thing to keep in mind: As per the specification, a request to a JSON:API server has to include theAccept
header 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
Observable
converted to aPromise
. TheAccept
header is set in the constructor so that all subsequent requests use this value.Example Node http context using axios
Example context for testing
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 followingContext
takes aTestApi
object and just returns a resolvedPromise
filled with data taken from theTestApi
object keyed bypathname
:You can then define a test API and use it in your unit tests: