-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
entities.js
97 lines (86 loc) · 2.58 KB
/
entities.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* External dependencies
*/
import { upperFirst, camelCase, map, find } from 'lodash';
/**
* Internal dependencies
*/
import { addEntities } from './actions';
import { apiFetch, select } from './controls';
export const DEFAULT_ENTITY_KEY = 'id';
export const defaultEntities = [
{ name: 'postType', kind: 'root', key: 'slug', baseURL: '/wp/v2/types' },
{ name: 'media', kind: 'root', baseURL: '/wp/v2/media', plural: 'mediaItems' },
{ name: 'taxonomy', kind: 'root', key: 'slug', baseURL: '/wp/v2/taxonomies', plural: 'taxonomies' },
];
export const kinds = [
{ name: 'postType', loadEntities: loadPostTypeEntities },
{ name: 'taxonomy', loadEntities: loadTaxonomyEntities },
];
/**
* Returns the list of post type entities.
*
* @return {Promise} Entities promise
*/
function* loadPostTypeEntities() {
const postTypes = yield apiFetch( { path: '/wp/v2/types?context=edit' } );
return map( postTypes, ( postType, name ) => {
return {
kind: 'postType',
baseURL: '/wp/v2/' + postType.rest_base,
name,
};
} );
}
/**
* Returns the list of the taxonomies entities.
*
* @return {Promise} Entities promise
*/
function* loadTaxonomyEntities() {
const taxonomies = yield apiFetch( { path: '/wp/v2/taxonomies?context=edit' } );
return map( taxonomies, ( taxonomy, name ) => {
return {
kind: 'taxonomy',
baseURL: '/wp/v2/' + taxonomy.rest_base,
name,
};
} );
}
/**
* Returns the entity's getter method name given its kind and name.
*
* @param {string} kind Entity kind.
* @param {string} name Entity name.
* @param {string} prefix Function prefix.
* @param {boolean} usePlural Whether to use the plural form or not.
*
* @return {string} Method name
*/
export const getMethodName = ( kind, name, prefix = 'get', usePlural = false ) => {
const entity = find( defaultEntities, { kind, name } );
const kindPrefix = kind === 'root' ? '' : upperFirst( camelCase( kind ) );
const nameSuffix = upperFirst( camelCase( name ) ) + ( usePlural ? 's' : '' );
const suffix = usePlural && entity.plural ? upperFirst( camelCase( entity.plural ) ) : nameSuffix;
return `${ prefix }${ kindPrefix }${ suffix }`;
};
/**
* Loads the kind entities into the store.
*
* @param {string} kind Kind
*
* @return {Array} Entities
*/
export function* getKindEntities( kind ) {
let entities = yield select( 'getEntitiesByKind', kind );
if ( entities && entities.length !== 0 ) {
return entities;
}
const kindConfig = find( kinds, { name: kind } );
if ( ! kindConfig ) {
return [];
}
entities = yield kindConfig.loadEntities();
yield addEntities( entities );
return entities;
}