forked from polkadot-developers/substrate-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
77 lines (71 loc) · 2.07 KB
/
gatsby-node.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
/* eslint-disable */
const { createPageRedirects } = require('./gatsby-node/create-redirects.js');
const { createDocsPages } = require('./gatsby-node/create-pages.js');
exports.createPages = async props => {
createPageRedirects(props);
await Promise.all([createDocsPages(props)]);
};
const { addSlugFieldToMarkdown, addPathFieldToMarkdown } = require('./gatsby-node/on-create-node.js');
exports.onCreateNode = props => {
const { node } = props;
if (node.internal.type === `MarkdownRemark`) {
addSlugFieldToMarkdown(props);
addPathFieldToMarkdown(props);
}
};
const { GraphQLJSONObject } = require(`graphql-type-json`)
const striptags = require(`striptags`)
const lunr = require(`lunr`)
exports.createResolvers = ({ cache, createResolvers }) => {
createResolvers({
Query: {
LunrIndex: {
type: GraphQLJSONObject,
resolve: (source, args, context, info) => {
const markdownNodes = context.nodeModel.getAllNodes({
type: `MarkdownRemark`,
})
const type = info.schema.getType(`MarkdownRemark`)
return createIndex(markdownNodes, type, cache)
},
},
},
})
}
const createIndex = async (markdownNodes, type, cache) => {
const cacheKey = `IndexLunr`
const cached = await cache.get(cacheKey)
if (cached) {
return cached
}
const documents = []
const store = {}
for (const node of markdownNodes) {
const {path} = node.fields
const title = node.frontmatter.title
const [html, excerpt] = await Promise.all([
type.getFields().html.resolve(node),
type.getFields().excerpt.resolve(node, { pruneLength: 40 }),
])
documents.push({
path: node.fields.path,
title: node.frontmatter.title,
content: striptags(html),
})
store[path] = {
title,
excerpt,
}
}
const index = lunr(function() {
this.ref(`path`)
this.field(`title`)
this.field(`content`)
for (const doc of documents) {
this.add(doc)
}
})
const json = { index: index.toJSON(), store }
await cache.set(cacheKey, json)
return json
}