-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathimport.js
54 lines (50 loc) · 1.31 KB
/
import.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
/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';
/**
* Internal dependencies
*/
import { readTextFile } from './file';
/**
* Import a reusable block from a JSON file.
*
* @param {File} file File.
* @return {Promise} Promise returning the imported reusable block.
*/
async function importReusableBlock( file ) {
const fileContent = await readTextFile( file );
let parsedContent;
try {
parsedContent = JSON.parse( fileContent );
} catch ( e ) {
throw new Error( 'Invalid JSON file' );
}
if (
parsedContent.__file !== 'wp_block' ||
! parsedContent.title ||
! parsedContent.content ||
typeof parsedContent.title !== 'string' ||
typeof parsedContent.content !== 'string' ||
( parsedContent.syncStatus &&
typeof parsedContent.syncStatus !== 'string' )
) {
throw new Error( 'Invalid pattern JSON file' );
}
const postType = await apiFetch( { path: `/wp/v2/types/wp_block` } );
const reusableBlock = await apiFetch( {
path: `/wp/v2/${ postType.rest_base }`,
data: {
title: parsedContent.title,
content: parsedContent.content,
status: 'publish',
meta:
parsedContent.syncStatus === 'unsynced'
? { wp_pattern_sync_status: parsedContent.syncStatus }
: undefined,
},
method: 'POST',
} );
return reusableBlock;
}
export default importReusableBlock;