Resource Templates

A resource template describes how Dojo resources interact with it’s data-source based on the options passed. Resource templates are statically defined and used through an application to power “resource aware” widgets. There are two types of ResourceTemplate that can be used, a standard template and a template that accepts initialization options.

A ResourceTemplate consists of two APIs:

  • read()
    • The function responsible for fetching the resource data based on the ResourceReadRequest and setting it in the store.
  • find()
    • The function responsible for finding an item in the resource data based on the ResourceFindRequest and setting it in the store.

A ResourceTemplateWithInit adds an additional init API

  • init()
    • An initializer function designed to deal with data passed to widgets with the template.
  1. interface ResourceTemplate<S = {}, T = {}> {
  2. read: ResourceRead<S>;
  3. find: ResourceFind<S>;
  4. }
  5. interface ResourceTemplateWithInit<S = {}, T = {}> {
  6. read: ResourceRead<S>;
  7. find: ResourceFind<S>;
  8. init: ResourceInit<S>;
  9. }

Resource Controls

ResourceControls are injected as the second argument to all the ResourceTemplate APIs and need to be used to get existing cached data from the resource store and put items into the store.

  1. export interface ResourceGet<S> {
  2. (request?: ResourceReadRequest<S>): ResourceReadResponse<S>;
  3. }
  4. export interface ResourcePut<S> {
  5. (readResponse: ResourceReadResponse<S>, readRequest: ResourceReadRequest<S>): void;
  6. (findResponse: ResourceFindResponse<S> | undefined, findRequest: ResourceFindRequest<S>): void;
  7. }
  8. export interface ResourceControls<S> {
  9. get: ResourceGet<S>;
  10. put: ResourcePut<S>;
  11. }

read()

The ResourceTemplate.read function is responsible for fetching requested data for the resource and setting it in the store using the put resource control. There are no restrictions to how the data is sourced as long as the ResourceReadResponse is set in the store using the put resource control.

  1. interface ResourceRead<S> {
  2. (request: ResourceReadRequest<S>, controls: ResourceControls<S>): void | Promise<void>;
  3. }

The ResourceReadRequest has the offset, page size and query of the request. The query is a an object with the key mapping to a key of the resource item data interface for the associated value.

  1. type ResourceQuery<S> = { [P in keyof S]?: any };
  2. interface ResourceReadRequest<S> {
  3. offset: number;
  4. size: number;
  5. query: ResourceQuery<S>;
  6. }

find()

The ResourceTemplate.find function is responsible for finding specific items within a resource based on the find criteria and setting it in the store using the put resource control. There are no restrictions to how the data is found as long as the ResourceFindResponse is set in the store using the put resource control.

  1. export interface ResourceFind<S> {
  2. (options: ResourceFindRequest<S>, controls: ResourceControls<S>): void | Promise<void>;
  3. }

The ResourceFindRequest has the current resource options, query, type and start index for the find request. The query is the same as the query object used with ResourceFindRequest, an object with the key mapping to a key of the resource item data interface for the associated value.

  1. type FindType = 'exact' | 'contains' | 'start';
  2. interface ResourceFindRequest<S> {
  3. options: ResourceOptions<S>;
  4. query: ResourceQuery<S>;
  5. start: number;
  6. type: FindType;
  7. }
  1. import { createResourceTemplate } from '@dojo/framework/core/middleware/resources';
  2. interface User {
  3. firsName: string;
  4. lastName: string;
  5. username: string;
  6. email: string;
  7. }

The type describes how to use the query to find the item in the resource, there are three different types.

  • contains (default)
    • Requesting an item where the value contains the the query item value
  • exact
    • Requesting an item that are an exact match of the query value
  • start
    • Requesting an item that where the value starts with the query value

init()

The init function is used to deal with options passed with the template using the resource middleware. These options are defined when creating the template using createResourceTemplateWithInit as the second generic parameter.

  1. import { createResourceTemplateWithInit } from '@dojo/framework/core/middleware/resources';
  2. // only showing the init api
  3. const template = createResourceTemplateWithInit<{ foo: string }, { data: { foo: string; }[]; extra: number; }>({
  4. init: (options, controls) {
  5. // the options matches the type passed as the second generic
  6. const { data, extra } = options;
  7. // use the controls to work with the store, for example store the init data
  8. controls.put({ data, total: data.length});
  9. }
  10. });
  11. interface ResourceInitRequest<S> {
  12. id: string;
  13. data: S[];
  14. }
  15. export interface ResourceInit<S, I> {
  16. (request: I & { id: string; }, controls: ResourceControls<S>): void;
  17. }

The init options are injected into the function along with the standard ResourceControls to be used to add the initialize the resource store.

Memory Resource Templates

Dojo resources offers a pre-configured memory resource template that implements the complete resource template API. The memory template is designed to work with data passed to a widget when using the template that initializes the resource store for the template. The memory template is created using the createMemoryResourceTemplate factory from @dojo/framework/core/middleware/resources, with the type of the resource data being passed to the factory.

MyWidget.tsx

  1. import { create, tsx } from '@dojo/framework/core/vdom';
  2. import { createMemoryResourceTemplate, createResourceMiddleware } from '@dojo/framework/core/middleware/resources';
  3. interface ResourceItem {
  4. value: string;
  5. }
  6. interface MyWidgetProperties {
  7. items: ResourceItem[];
  8. }
  9. const resource = createResourceMiddleware();
  10. const factory = create({ resource }).properties<MyWidgetProperties>();
  11. const template = createMemoryResourceTemplate<ResourceItem>();
  12. export default factory(function MyWidget({ id, properties, middleware: { resource } }) {
  13. const { items } = properties();
  14. return <MyResourceAwareWidget resource={resource({ template, initOptions: { id, data: items } } )}>
  15. });

For more information please see the Using Resource Templates.

Custom Resource Templates

To connect a resource to an custom data-source, such as a RESTful API the createResourceTemplate() factory can be used. At a minimum the read API needs to be fulfilled with the additional init and find optional.

myResourceTemplate.ts

  1. import { createResourceTemplate } from '@dojo/framework/core/middleware/resources';
  2. interface MyResource {
  3. id: string;
  4. name: string;
  5. email: string;
  6. }
  7. export default createResourceTemplate<MyResource>({
  8. read: async (request: ResourceReadRequest, controls: ResourceControls) => {
  9. const { offset, size, query } = request;
  10. // use the request details to fetch the required set of data
  11. const url = `https://my-data-source.com?size=${size}&offset=${offset}&query${JSON.stringify(query)}`;
  12. const response = await fetch(url);
  13. const json = await response.json();
  14. controls.put({ data: json.data, total: json.total }, request);
  15. },
  16. find: (request: ResourceFindRequest, controls: ResourceControls) => {
  17. const { query, options, start, type } = request;
  18. // use the start, query, type and options to find an item from the data-source
  19. const url = `https://my-data-source.com/?start=${start}&type=${type}&find${JSON.stringify(query)}`;
  20. const response = await fetch(url);
  21. const json = await response.json();
  22. controls.put({ item: json.item, index: json.index }, request);
  23. }
  24. });

Create a Resource Template with initialization options

If the resource template needs to support custom initialization the createResourceTemplateWithInit can be used, which requires the template to have an init API that will be called when a backing resource is created. The initialize options required are typed using the second generic on the factory function.

  1. import { createResourceTemplateWithInit } from '@dojo/framework/core/middleware/resources';
  2. interface MyResource {
  3. id: string;
  4. name: string;
  5. email: string;
  6. }
  7. export default createResourceTemplateWithInit<MyResource, { data: MyResource[] }>({
  8. init: (request: { id: string } & { data: MyResource[] }, controls: ResourceControls) => {
  9. const { data } = request;
  10. // adds any data passed with the template to resource store
  11. controls.put(data);
  12. },
  13. read: async (request: ResourceReadRequest, controls: ResourceControls) => {
  14. const { offset, size, query } = request;
  15. // use the request details to fetch the required set of data
  16. const url = `https://my-data-source.com?size=${size}&offset=${offset}&query${JSON.stringify(query)}`;
  17. const response = await fetch(url);
  18. const json = await response.json();
  19. controls.put({ data: json.data, total: json.total }, request);
  20. },
  21. find: (request: ResourceFindRequest, controls: ResourceControls) => {
  22. const { query, options, start, type } = request;
  23. // use the start, query, type and options to find an item from the data-source
  24. const url = `https://my-data-source.com/?start=${start}&type=${type}&find${JSON.stringify(query)}`;
  25. const response = await fetch(url);
  26. const json = await response.json();
  27. controls.put({ item: json.item, index: json.index }, request);
  28. }
  29. });

Typing Resource Templates

The resource template factories all accept a generic that is used to type the shape of the resource data. It is highly recommended to provide typings to the template so that when the template is passed to a widget the typings for data and transform can be inferred correctly. As referenced in the previous examples, typing a resource requires passing the resource data type interface on creation of the template.

userResourceTemplate.ts

  1. import { createResourceTemplate } from '@dojo/framework/core/middleware/resources';
  2. interface User {
  3. firsName: string;
  4. lastName: string;
  5. username: string;
  6. email: string;
  7. }
  8. export default createResourceTemplate<User>({
  9. // the template implementation
  10. });