-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
185 lines (137 loc) · 4.32 KB
/
index.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
const groq = require( 'groq-js' );
const matchAll = require( 'string.prototype.matchall' );
const murmurhash = require( './murmur' );
const path = require( 'path' );
const { reporter } = require( './utils' );
const ROOT = path.resolve( __dirname, '../..' );
const GROQ_DIR = process.env.NODE_ENV === 'development' ? `${ROOT}/.cache/groq` : `${ROOT}/public/static/groq`;
/**
* Use directory settings throughout plugin.
*/
exports.groqDirectories = { ROOT, GROQ_DIR };
/**
* Hook to mimic Gatsby's static query.
* During extraction the plugin fines and extracts these queries
* and stores them in a directory. During SSR and runtime this function
* fetches the query reults from wherever they are being cached.
*
* @param {string} query
* @return {array}
*/
exports.useGroqQuery = query => {
const hash = murmurhash( query );
try {
const result = require( `${process.env.GROQ_DIR}/${hash}.json` );
return result;
}
catch( err ) {
console.warn( err );
}
}
/**
* Groq query helper function.
*
* @param {string} rawQuery
* @param {map} dataset
* @param {Object} options
* @param {Object} options.fragments
* @param {Object} options.params
* @param {string} options.file For debugging.
* @return {Object} Array of results along with final query and query string to get hashed.
*/
exports.runQuery = async ( rawQuery, dataset, options = {} ) => {
const { file, fragments, params } = options;
let query = rawQuery;
// Check if query has fragment.
const hasFragment = query.includes( '${' );
if( hasFragment ) {
query = processFragments( query, fragments );
}
const queryToHash = query;
query = processJoins( query );
try {
const strippedQuery = query.replace( /`/g, '', );
const parsedQuery = groq.parse( strippedQuery );
const value = await groq.evaluate( parsedQuery, { dataset } );
const result = await value.get();
return { result, finalQuery: query, queryToHash }
}
catch( err ) {
console.error( file );
reporter.error( `${err}` );
reporter.error( `Query: ${query}` );
return err;
}
}
/**
* Process joins.
*
* @param {string} query
* @return {string}
*/
function processJoins( query ) {
// We need to figure out a clean way to get plugin options...
let processedQuery = query;
if( processedQuery.includes( '->' ) ) {
const optionsDir = process.env.GROQ_DIR || GROQ_DIR;
const { autoRefs, referenceMatcher } = require( `${optionsDir}/options` );
const matchField = referenceMatcher || 'id';
const refOption = !! autoRefs ? '._ref' : '';
const search = `\\S+->\\w*`;
const regex = new RegExp( search, 'g' );
const matches = [ ... matchAll( processedQuery, regex ) ];
if( !! matches.length ) {
for( let match of matches ) {
const matchText = match[0];
// For now we're skipping Sanity .assets since they work by default.
if( matchText.includes( '.asset->' ) ) {
continue;
}
const field = matchText.replace( '->', '' );
let replace = null;
// Single refs.
if( ! field.includes( '[]' ) ) {
replace = `*[ ${matchField} == ^.${field}${refOption} ][0]`;
}
// Arrays.
else {
replace = `*[ ${matchField} in ^.${field}${refOption} ]`;
}
processedQuery = processedQuery.replace( matchText, replace );
}
}
}
return processedQuery;
}
/**
* Process fragments.
*
* @param {string} query
* @param {object} fragments
* @return {string}
*/
function processFragments( query, fragments ) {
let processedQuery = query;
if( ! fragments || ! Object.keys( fragments ).length ) {
reporter.warn( 'Query contains fragments but no index provided.' );
return null;
}
// For now we are just going through all fragments and running
// simple string replacement.
for( let [ name, value ] of Object.entries( fragments ) ) {
if( ! processedQuery.includes( name ) ) {
continue;
}
// Process string.
if( typeof value === 'string' ) {
const search = `\\$\\{(${name})\\}`;
const pattern = new RegExp( search, 'g' );
processedQuery = processedQuery.replace( pattern, value );
}
// Process function.
// else if( typeof value === 'function' ) {
//
// }
}
return processedQuery;
}