-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpersistQuery.js
More file actions
223 lines (208 loc) · 6.67 KB
/
persistQuery.js
File metadata and controls
223 lines (208 loc) · 6.67 KB
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
const https = require('https');
const path = require('path');
const GraphQLLanguage = require('graphql/language');
const {parse, print} = require('graphql');
require('dotenv').config();
require('dotenv').config({path: path.resolve(process.cwd(), '.env.local')});
if (
(!process.env.REPOSITORY_FIXED_VARIABLES &&
// Backwards compat with older apps that started with razzle
(process.env.RAZZLE_GITHUB_REPO_OWNER &&
process.env.RAZZLE_GITHUB_REPO_NAME)) ||
(process.env.NEXT_PUBLIC_GITHUB_REPO_OWNER &&
process.env.NEXT_PUBLIC_GITHUB_REPO_NAME) ||
(process.env.VERCEL_GITHUB_ORG && process.env.VERCEL_GITHUB_REPO)
) {
const repoName =
process.env['RAZZLE_GITHUB_REPO_NAME'] ||
process.env['NEXT_PUBLIC_GITHUB_REPO_NAME'] ||
process.env['VERCEL_GITHUB_REPO'];
const repoOwner =
process.env['RAZZLE_GITHUB_REPO_OWNER'] ||
process.env['NEXT_PUBLIC_GITHUB_REPO_OWNER'] ||
process.env['VERCEL_GITHUB_ORG'];
process.env[
'REPOSITORY_FIXED_VARIABLES'
] = `{"repoName": "${repoName}", "repoOwner": "${repoOwner}"}`;
}
const PERSIST_QUERY_MUTATION = `
mutation PersistQuery(
$freeVariables: [String!]!
$appId: String!
$accessToken: String
$query: String!
$fixedVariables: JSON
$cacheStrategy: OneGraphPersistedQueryCacheStrategyArg
) {
oneGraph {
createPersistedQuery(
input: {
query: $query
accessToken: $accessToken
appId: $appId
cacheStrategy: $cacheStrategy
freeVariables: $freeVariables
fixedVariables: $fixedVariables
}
) {
persistedQuery {
id
}
}
}
}
`;
async function persistQuery(queryText) {
const ast = parse(queryText, {noLocation: true});
const freeVariables = new Set([]);
let accessToken = null;
let fixedVariables = null;
let cacheSeconds = null;
let transformedAst = GraphQLLanguage.visit(ast, {
OperationDefinition: {
enter(node) {
for (const directive of node.directives) {
if (directive.name.value === 'persistedQueryConfiguration') {
const accessTokenArg = directive.arguments.find(
a => a.name.value === 'accessToken',
);
const fixedVariablesArg = directive.arguments.find(
a => a.name.value === 'fixedVariables',
);
const freeVariablesArg = directive.arguments.find(
a => a.name.value === 'freeVariables',
);
const cacheSecondsArg = directive.arguments.find(
a => a.name.value === 'cacheSeconds',
);
if (accessTokenArg) {
const envArg = accessTokenArg.value.fields.find(
f => f.name.value === 'environmentVariable',
);
if (envArg) {
if (accessToken) {
throw new Error(
'Access token is already defined for operation=' +
node.name.value,
);
}
const envVar = envArg.value.value;
accessToken = process.env[envVar];
if (!accessToken) {
throw new Error(
'Cannot persist query. Missing environment variable `' +
envVar +
'`.',
);
}
}
}
if (fixedVariablesArg) {
const envArg = fixedVariablesArg.value.fields.find(
f => f.name.value === 'environmentVariable',
);
if (envArg) {
if (fixedVariables) {
throw new Error(
'fixedVariables are already defined for operation=' +
node.name.value,
);
}
const envVar = envArg.value.value;
fixedVariables = JSON.parse(process.env[envVar]);
if (!fixedVariables) {
throw new Error(
'Cannot persist query. Missing environment variable `' +
envVar +
'`.',
);
}
}
}
if (freeVariablesArg) {
for (const v of freeVariablesArg.value.values) {
freeVariables.add(v.value);
}
}
if (cacheSecondsArg) {
cacheSeconds = parseFloat(cacheSecondsArg.value.value);
}
}
}
return {
...node,
directives: node.directives.filter(
d => d.name.value !== 'persistedQueryConfiguration',
),
};
},
},
});
const appId =
process.env.NEXT_PUBLIC_ONEGRAPH_APP_ID ||
// Backwards compat with older apps that started with razzle
process.env.RAZZLE_ONEGRAPH_APP_ID;
const variables = {
query: print(transformedAst),
// This is your app's app id, edit `/.env` to change it
appId,
accessToken: accessToken || null,
freeVariables: [...freeVariables],
fixedVariables: fixedVariables,
cacheStrategy: cacheSeconds
? {
timeToLiveSeconds: cacheSeconds,
}
: null,
};
const body = JSON.stringify({
query: PERSIST_QUERY_MUTATION,
variables,
});
function persist(appId) {
return new Promise((resolve, reject) => {
let data = '';
const req = https.request(
{
hostname: 'serve.onegraph.com',
port: 443,
path: `/graphql?app_id=${appId}`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': body.length,
Authorization: 'Bearer ' + process.env.OG_DASHBOARD_ACCESS_TOKEN,
},
},
(res) => {
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
const resp = JSON.parse(data);
if (resp.errors) {
reject(
new Error(
'Error persisting query, errors=' +
JSON.stringify(resp.errors),
),
);
} else {
resolve(
resp.data.oneGraph.createPersistedQuery.persistedQuery.id,
);
}
});
},
);
req.write(body);
req.end();
});
}
return persist(appId).catch(() =>
// This is the app id for the OneGraph dashboard. Some older persist query tokens will require
// you to use this id. If persisting with the oneblog app id fails, then try with the dashboard id.
persist('0b066ba6-ed39-4db8-a497-ba0be34d5b2a'),
);
}
exports.default = persistQuery;