我正在使用Gatsby的createResolver
API将markdown转换为html。它可以在数据的最高级别正常工作。但是,我无法在更深层嵌套的数组上使用它。
正在起作用:
function markdownToHTMLResolver(nodeType, node, type) {
return {
[nodeType]: {
[`${node}_html`]: {
type: type,
resolve: (source, args, context, info) => {
return remark().use(html).processSync(source[node]).contents;
},
},
},
};
}
exports.createResolvers = ({ createResolvers }) => {
const resolvers = {
...markdownToHTMLResolver(BLOG_NODE_TYPE, 'body', 'String'),
...markdownToHTMLResolver(FRONT_NODE_TYPE, 'body', 'String'),
...markdownToHTMLResolver(EVENT_NODE_TYPE, 'body', 'String'),
...markdownToHTMLPageResolver(PAGE_NODE_TYPE, 'body', 'String'),
};
createResolvers(resolvers);
};
这适用于我的REST API中的数据,其结构如下:
{
title: 'Title',
body: '## Heading 2 \n\nParagraph Text.'
}
但是,我不太想将它用于这样的嵌套数据:
{
title: 'Title',
body: '## Heading 2 \n\nParagraph Text.'
list: {
data: [
{ title: 'Nested Title 1', body: 'Nested body markdown text 1.'},
{ title: 'Nested Title 2', body: 'Nested body markdown text 2.'},
{ title: 'Nested Title 3', body: 'Nested body markdown text 3.'},
[
}
}
我不确定此嵌套数据的类型是什么。我已经尝试过类似的方法,但是显然存在缺陷:
function markdownToHTMLPageResolver(nodeType, node, type) {
return {
[nodeType]: {
[`${node}_html`]: {
type: type,
resolve: (source, args, context, info) => {
return remark().use(html).processSync(source[node]).contents;
},
},
list_html: {
type: ['String'],
resolve: (source, args, context, info) => {
return source.list.data.forEach((item) => ({
title: item.title,
body: remark().use(html).processSync(source[node]).contents,
}));
},
},
},
};
}
任何方向或帮助将不胜感激。
答案 0 :(得分:1)
所以我想我明白了。我可以使用__typename
在GraphiQL接口中发现推断的类型。然后,我可以遍历数据并像这样处理减价:
list_html: {
type: 'PageList',
resolve: (source, args, context, info) => {
const dataArray = source.list.data.map((item) => {
return {
title: item.title,
body: remark().use(html).processSync(item.body).contents,
};
});
return {
data: dataArray,
};
},
},
保持对象结构与原始对象相同似乎很重要。