-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
resolvers.js
605 lines (545 loc) · 16.4 KB
/
resolvers.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
/**
* External dependencies
*/
import { camelCase } from 'change-case';
/**
* WordPress dependencies
*/
import { addQueryArgs } from '@wordpress/url';
import apiFetch from '@wordpress/api-fetch';
/**
* Internal dependencies
*/
import { STORE_NAME } from './name';
import { getOrLoadEntitiesConfig, DEFAULT_ENTITY_KEY } from './entities';
import { forwardResolver, getNormalizedCommaSeparable } from './utils';
/**
* Requests authors from the REST API.
*
* @param {Object|undefined} query Optional object of query parameters to
* include with request.
*/
export const getAuthors =
( query ) =>
async ( { dispatch } ) => {
const path = addQueryArgs(
'/wp/v2/users/?who=authors&per_page=100',
query
);
const users = await apiFetch( { path } );
dispatch.receiveUserQuery( path, users );
};
/**
* Requests the current user from the REST API.
*/
export const getCurrentUser =
() =>
async ( { dispatch } ) => {
const currentUser = await apiFetch( { path: '/wp/v2/users/me' } );
dispatch.receiveCurrentUser( currentUser );
};
/**
* Requests an entity's record from the REST API.
*
* @param {string} kind Entity kind.
* @param {string} name Entity name.
* @param {number|string} key Record's key
* @param {Object|undefined} query Optional object of query parameters to
* include with request. If requesting specific
* fields, fields must always include the ID.
*/
export const getEntityRecord =
( kind, name, key = '', query ) =>
async ( { select, dispatch } ) => {
const configs = await dispatch( getOrLoadEntitiesConfig( kind ) );
const entityConfig = configs.find(
( config ) => config.name === name && config.kind === kind
);
if ( ! entityConfig || entityConfig?.__experimentalNoFetch ) {
return;
}
const lock = await dispatch.__unstableAcquireStoreLock(
STORE_NAME,
[ 'entities', 'records', kind, name, key ],
{ exclusive: false }
);
try {
if ( query !== undefined && query._fields ) {
// If requesting specific fields, items and query association to said
// records are stored by ID reference. Thus, fields must always include
// the ID.
query = {
...query,
_fields: [
...new Set( [
...( getNormalizedCommaSeparable( query._fields ) ||
[] ),
entityConfig.key || DEFAULT_ENTITY_KEY,
] ),
].join(),
};
}
// Disable reason: While true that an early return could leave `path`
// unused, it's important that path is derived using the query prior to
// additional query modifications in the condition below, since those
// modifications are relevant to how the data is tracked in state, and not
// for how the request is made to the REST API.
// eslint-disable-next-line @wordpress/no-unused-vars-before-return
const path = addQueryArgs(
entityConfig.baseURL + ( key ? '/' + key : '' ),
{
...entityConfig.baseURLParams,
...query,
}
);
if ( query !== undefined ) {
query = { ...query, include: [ key ] };
// The resolution cache won't consider query as reusable based on the
// fields, so it's tested here, prior to initiating the REST request,
// and without causing `getEntityRecords` resolution to occur.
const hasRecords = select.hasEntityRecords( kind, name, query );
if ( hasRecords ) {
return;
}
}
const record = await apiFetch( { path } );
dispatch.receiveEntityRecords( kind, name, record, query );
} finally {
dispatch.__unstableReleaseStoreLock( lock );
}
};
/**
* Requests an entity's record from the REST API.
*/
export const getRawEntityRecord = forwardResolver( 'getEntityRecord' );
/**
* Requests an entity's record from the REST API.
*/
export const getEditedEntityRecord = forwardResolver( 'getEntityRecord' );
/**
* Requests the entity's records from the REST API.
*
* @param {string} kind Entity kind.
* @param {string} name Entity name.
* @param {Object?} query Query Object. If requesting specific fields, fields
* must always include the ID.
*/
export const getEntityRecords =
( kind, name, query = {} ) =>
async ( { dispatch } ) => {
const configs = await dispatch( getOrLoadEntitiesConfig( kind ) );
const entityConfig = configs.find(
( config ) => config.name === name && config.kind === kind
);
if ( ! entityConfig || entityConfig?.__experimentalNoFetch ) {
return;
}
const lock = await dispatch.__unstableAcquireStoreLock(
STORE_NAME,
[ 'entities', 'records', kind, name ],
{ exclusive: false }
);
try {
if ( query._fields ) {
// If requesting specific fields, items and query association to said
// records are stored by ID reference. Thus, fields must always include
// the ID.
query = {
...query,
_fields: [
...new Set( [
...( getNormalizedCommaSeparable( query._fields ) ||
[] ),
entityConfig.key || DEFAULT_ENTITY_KEY,
] ),
].join(),
};
}
const path = addQueryArgs( entityConfig.baseURL, {
...entityConfig.baseURLParams,
...query,
} );
let records = Object.values( await apiFetch( { path } ) );
// If we request fields but the result doesn't contain the fields,
// explicitly set these fields as "undefined"
// that way we consider the query "fullfilled".
if ( query._fields ) {
records = records.map( ( record ) => {
query._fields.split( ',' ).forEach( ( field ) => {
if ( ! record.hasOwnProperty( field ) ) {
record[ field ] = undefined;
}
} );
return record;
} );
}
dispatch.receiveEntityRecords( kind, name, records, query );
// When requesting all fields, the list of results can be used to
// resolve the `getEntityRecord` selector in addition to `getEntityRecords`.
// See https://github.com/WordPress/gutenberg/pull/26575
if ( ! query?._fields && ! query.context ) {
const key = entityConfig.key || DEFAULT_ENTITY_KEY;
const resolutionsArgs = records
.filter( ( record ) => record[ key ] )
.map( ( record ) => [ kind, name, record[ key ] ] );
dispatch( {
type: 'START_RESOLUTIONS',
selectorName: 'getEntityRecord',
args: resolutionsArgs,
} );
dispatch( {
type: 'FINISH_RESOLUTIONS',
selectorName: 'getEntityRecord',
args: resolutionsArgs,
} );
}
} finally {
dispatch.__unstableReleaseStoreLock( lock );
}
};
getEntityRecords.shouldInvalidate = ( action, kind, name ) => {
return (
( action.type === 'RECEIVE_ITEMS' || action.type === 'REMOVE_ITEMS' ) &&
action.invalidateCache &&
kind === action.kind &&
name === action.name
);
};
/**
* Requests the current theme.
*/
export const getCurrentTheme =
() =>
async ( { dispatch, resolveSelect } ) => {
const activeThemes = await resolveSelect.getEntityRecords(
'root',
'theme',
{ status: 'active' }
);
dispatch.receiveCurrentTheme( activeThemes[ 0 ] );
};
/**
* Requests theme supports data from the index.
*/
export const getThemeSupports = forwardResolver( 'getCurrentTheme' );
/**
* Requests a preview from the from the Embed API.
*
* @param {string} url URL to get the preview for.
*/
export const getEmbedPreview =
( url ) =>
async ( { dispatch } ) => {
try {
const embedProxyResponse = await apiFetch( {
path: addQueryArgs( '/oembed/1.0/proxy', { url } ),
} );
dispatch.receiveEmbedPreview( url, embedProxyResponse );
} catch ( error ) {
// Embed API 404s if the URL cannot be embedded, so we have to catch the error from the apiRequest here.
dispatch.receiveEmbedPreview( url, false );
}
};
/**
* Checks whether the current user can perform the given action on the given
* REST resource.
*
* @param {string} requestedAction Action to check. One of: 'create', 'read', 'update',
* 'delete'.
* @param {string} resource REST resource to check, e.g. 'media' or 'posts'.
* @param {?string} id ID of the rest resource to check.
*/
export const canUser =
( requestedAction, resource, id ) =>
async ( { dispatch, registry } ) => {
const { hasStartedResolution } = registry.select( STORE_NAME );
const resourcePath = id ? `${ resource }/${ id }` : resource;
const retrievedActions = [ 'create', 'read', 'update', 'delete' ];
if ( ! retrievedActions.includes( requestedAction ) ) {
throw new Error( `'${ requestedAction }' is not a valid action.` );
}
// Prevent resolving the same resource twice.
for ( const relatedAction of retrievedActions ) {
if ( relatedAction === requestedAction ) {
continue;
}
const isAlreadyResolving = hasStartedResolution( 'canUser', [
relatedAction,
resource,
id,
] );
if ( isAlreadyResolving ) {
return;
}
}
let response;
try {
response = await apiFetch( {
path: `/wp/v2/${ resourcePath }`,
method: 'OPTIONS',
parse: false,
} );
} catch ( error ) {
// Do nothing if our OPTIONS request comes back with an API error (4xx or
// 5xx). The previously determined isAllowed value will remain in the store.
return;
}
// Optional chaining operator is used here because the API requests don't
// return the expected result in the native version. Instead, API requests
// only return the result, without including response properties like the headers.
const allowHeader = response.headers?.get( 'allow' );
const allowedMethods = allowHeader?.allow || allowHeader || '';
const permissions = {};
const methods = {
create: 'POST',
read: 'GET',
update: 'PUT',
delete: 'DELETE',
};
for ( const [ actionName, methodName ] of Object.entries( methods ) ) {
permissions[ actionName ] = allowedMethods.includes( methodName );
}
for ( const action of retrievedActions ) {
dispatch.receiveUserPermission(
`${ action }/${ resourcePath }`,
permissions[ action ]
);
}
};
/**
* Checks whether the current user can perform the given action on the given
* REST resource.
*
* @param {string} kind Entity kind.
* @param {string} name Entity name.
* @param {string} recordId Record's id.
*/
export const canUserEditEntityRecord =
( kind, name, recordId ) =>
async ( { dispatch } ) => {
const configs = await dispatch( getOrLoadEntitiesConfig( kind ) );
const entityConfig = configs.find(
( config ) => config.name === name && config.kind === kind
);
if ( ! entityConfig ) {
return;
}
const resource = entityConfig.__unstable_rest_base;
await dispatch( canUser( 'update', resource, recordId ) );
};
/**
* Request autosave data from the REST API.
*
* @param {string} postType The type of the parent post.
* @param {number} postId The id of the parent post.
*/
export const getAutosaves =
( postType, postId ) =>
async ( { dispatch, resolveSelect } ) => {
const { rest_base: restBase, rest_namespace: restNamespace = 'wp/v2' } =
await resolveSelect.getPostType( postType );
const autosaves = await apiFetch( {
path: `/${ restNamespace }/${ restBase }/${ postId }/autosaves?context=edit`,
} );
if ( autosaves && autosaves.length ) {
dispatch.receiveAutosaves( postId, autosaves );
}
};
/**
* Request autosave data from the REST API.
*
* This resolver exists to ensure the underlying autosaves are fetched via
* `getAutosaves` when a call to the `getAutosave` selector is made.
*
* @param {string} postType The type of the parent post.
* @param {number} postId The id of the parent post.
*/
export const getAutosave =
( postType, postId ) =>
async ( { resolveSelect } ) => {
await resolveSelect.getAutosaves( postType, postId );
};
/**
* Retrieve the frontend template used for a given link.
*
* @param {string} link Link.
*/
export const __experimentalGetTemplateForLink =
( link ) =>
async ( { dispatch, resolveSelect } ) => {
let template;
try {
// This is NOT calling a REST endpoint but rather ends up with a response from
// an Ajax function which has a different shape from a WP_REST_Response.
template = await apiFetch( {
url: addQueryArgs( link, {
'_wp-find-template': true,
} ),
} ).then( ( { data } ) => data );
} catch ( e ) {
// For non-FSE themes, it is possible that this request returns an error.
}
if ( ! template ) {
return;
}
const record = await resolveSelect.getEntityRecord(
'postType',
'wp_template',
template.id
);
if ( record ) {
dispatch.receiveEntityRecords(
'postType',
'wp_template',
[ record ],
{
'find-template': link,
}
);
}
};
__experimentalGetTemplateForLink.shouldInvalidate = ( action ) => {
return (
( action.type === 'RECEIVE_ITEMS' || action.type === 'REMOVE_ITEMS' ) &&
action.invalidateCache &&
action.kind === 'postType' &&
action.name === 'wp_template'
);
};
export const __experimentalGetCurrentGlobalStylesId =
() =>
async ( { dispatch, resolveSelect } ) => {
const activeThemes = await resolveSelect.getEntityRecords(
'root',
'theme',
{ status: 'active' }
);
const globalStylesURL =
activeThemes?.[ 0 ]?._links?.[ 'wp:user-global-styles' ]?.[ 0 ]
?.href;
if ( globalStylesURL ) {
const globalStylesObject = await apiFetch( {
url: globalStylesURL,
} );
dispatch.__experimentalReceiveCurrentGlobalStylesId(
globalStylesObject.id
);
}
};
export const __experimentalGetCurrentThemeBaseGlobalStyles =
() =>
async ( { resolveSelect, dispatch } ) => {
const currentTheme = await resolveSelect.getCurrentTheme();
const themeGlobalStyles = await apiFetch( {
path: `/wp/v2/global-styles/themes/${ currentTheme.stylesheet }`,
} );
dispatch.__experimentalReceiveThemeBaseGlobalStyles(
currentTheme.stylesheet,
themeGlobalStyles
);
};
export const __experimentalGetCurrentThemeGlobalStylesVariations =
() =>
async ( { resolveSelect, dispatch } ) => {
const currentTheme = await resolveSelect.getCurrentTheme();
const variations = await apiFetch( {
path: `/wp/v2/global-styles/themes/${ currentTheme.stylesheet }/variations`,
} );
dispatch.__experimentalReceiveThemeGlobalStyleVariations(
currentTheme.stylesheet,
variations
);
};
/**
* Fetches and returns the revisions of the current global styles theme.
*/
export const getCurrentThemeGlobalStylesRevisions =
() =>
async ( { resolveSelect, dispatch } ) => {
const globalStylesId =
await resolveSelect.__experimentalGetCurrentGlobalStylesId();
const record = globalStylesId
? await resolveSelect.getEntityRecord(
'root',
'globalStyles',
globalStylesId
)
: undefined;
const revisionsURL = record?._links?.[ 'version-history' ]?.[ 0 ]?.href;
if ( revisionsURL ) {
const resetRevisions = await apiFetch( {
url: revisionsURL,
} );
const revisions = resetRevisions?.map( ( revision ) =>
Object.fromEntries(
Object.entries( revision ).map( ( [ key, value ] ) => [
camelCase( key ),
value,
] )
)
);
dispatch.receiveThemeGlobalStyleRevisions(
globalStylesId,
revisions
);
}
};
getCurrentThemeGlobalStylesRevisions.shouldInvalidate = ( action ) => {
return (
action.type === 'SAVE_ENTITY_RECORD_FINISH' &&
action.kind === 'root' &&
! action.error &&
action.name === 'globalStyles'
);
};
export const getBlockPatterns =
() =>
async ( { dispatch } ) => {
const restPatterns = await apiFetch( {
path: '/wp/v2/block-patterns/patterns',
} );
const patterns = restPatterns?.map( ( pattern ) =>
Object.fromEntries(
Object.entries( pattern ).map( ( [ key, value ] ) => [
camelCase( key ),
value,
] )
)
);
dispatch( { type: 'RECEIVE_BLOCK_PATTERNS', patterns } );
};
export const getBlockPatternCategories =
() =>
async ( { dispatch } ) => {
const categories = await apiFetch( {
path: '/wp/v2/block-patterns/categories',
} );
dispatch( { type: 'RECEIVE_BLOCK_PATTERN_CATEGORIES', categories } );
};
export const getNavigationFallbackId =
() =>
async ( { dispatch } ) => {
const fallback = await apiFetch( {
path: addQueryArgs( '/wp-block-editor/v1/navigation-fallback', {
_embed: true,
} ),
} );
const record = fallback?._embedded?.self;
dispatch.receiveNavigationFallbackId( fallback?.id );
if ( record ) {
const invalidateNavigationQueries = true;
dispatch.receiveEntityRecords(
'postType',
'wp_navigation',
record,
undefined,
invalidateNavigationQueries
);
// Resolve to avoid further network requests.
dispatch.finishResolution( 'getEntityRecord', [
'postType',
'wp_navigation',
fallback?.id,
] );
}
};