@@ -10,7 +10,7 @@ import {isHierarchicalPostType} from './postTypes'
10
10
* @param {string } postType WP post type.
11
11
* @param {Number|string } id Post identifier.
12
12
* @param {string } idType Type of ID.
13
- * @return {? Object } Post data or null .
13
+ * @return {Object } Post data or error object .
14
14
*/
15
15
export default async function getPostTypeById ( postType , id , idType = 'SLUG' ) {
16
16
// Define single post query based on post type.
@@ -28,20 +28,34 @@ export default async function getPostTypeById(postType, id, idType = 'SLUG') {
28
28
// Retrieve post type query.
29
29
const query = postTypeQuery ?. [ postType ] ?? null
30
30
31
- // If no query is set for given post type, return.
31
+ // If no query is set for given post type, return error message .
32
32
if ( ! query ) {
33
- return null
33
+ return {
34
+ isError : true ,
35
+ message : `Post type \`${ postType } \` is not supported.`
36
+ }
34
37
}
35
38
36
39
// Get/create Apollo instance.
37
40
const apolloClient = initializeApollo ( )
38
41
39
42
// Execute query.
40
- const post = await apolloClient . query ( { query, variables : { id, idType} } )
43
+ const post = await apolloClient
44
+ . query ( { query, variables : { id, idType} } )
45
+ . then ( ( post ) => post ?. data ?. [ postType ] ?? null )
46
+ . catch ( ( error ) => {
47
+ return {
48
+ isError : true ,
49
+ message : error . message
50
+ }
51
+ } )
41
52
42
53
if ( ! post ) {
43
- return null
54
+ return {
55
+ isError : true ,
56
+ message : `An error occurred while trying to retrieve data for ${ postType } "${ id } ."`
57
+ }
44
58
}
45
59
46
- return post ?. data ?. [ postType ] ?? null
60
+ return post
47
61
}
0 commit comments