This repository has been archived by the owner on Jul 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 146
/
operations.js
99 lines (85 loc) · 2.57 KB
/
operations.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
/** @format */
/**
* External dependencies
*/
import apiFetch from '@wordpress/api-fetch';
/**
* WooCommerce dependencies
*/
import { stringifyQuery } from '@woocommerce/navigation';
/**
* Internal dependencies
*/
import { isResourcePrefix, getResourceIdentifier, getResourceName } from '../utils';
import { NAMESPACE } from '../constants';
function read( resourceNames, fetch = apiFetch ) {
return [ ...readNotes( resourceNames, fetch ), ...readNoteQueries( resourceNames, fetch ) ];
}
function update( resourceNames, data, fetch = apiFetch ) {
return [ ...updateNote( resourceNames, data, fetch ) ];
}
function readNoteQueries( resourceNames, fetch ) {
const filteredNames = resourceNames.filter( name => isResourcePrefix( name, 'note-query' ) );
return filteredNames.map( async resourceName => {
const query = getResourceIdentifier( resourceName );
const url = `${ NAMESPACE }/admin/notes${ stringifyQuery( query ) }`;
try {
const response = await fetch( {
parse: false,
path: url,
} );
const notes = await response.json();
const totalCount = parseInt( response.headers.get( 'x-wp-total' ) );
const ids = notes.map( note => note.id );
const noteResources = notes.reduce( ( resources, note ) => {
resources[ getResourceName( 'note', note.id ) ] = { data: note };
return resources;
}, {} );
return {
[ resourceName ]: {
data: ids,
totalCount,
},
...noteResources,
};
} catch ( error ) {
return { [ resourceName ]: { error } };
}
} );
}
function readNotes( resourceNames, fetch ) {
const filteredNames = resourceNames.filter( name => isResourcePrefix( name, 'note' ) );
return filteredNames.map( resourceName => readNote( resourceName, fetch ) );
}
function readNote( resourceName, fetch ) {
const id = getResourceIdentifier( resourceName );
const url = `${ NAMESPACE }/admin/notes/${ id }`;
return fetch( { path: url } )
.then( note => {
return { [ resourceName ]: { data: note } };
} )
.catch( error => {
return { [ resourceName ]: { error } };
} );
}
function updateNote( resourceNames, data, fetch ) {
const resourceName = 'note';
if ( resourceNames.includes( resourceName ) ) {
const { noteId, ...noteFields } = data[ resourceName ];
const url = `${ NAMESPACE }/admin/notes/${ noteId }`;
return [
fetch( { path: url, method: 'PUT', data: noteFields } )
.then( note => {
return { [ resourceName + ':' + noteId ]: { data: note } };
} )
.catch( error => {
return { [ resourceName + ':' + noteId ]: { error } };
} ),
];
}
return [];
}
export default {
read,
update,
};