Skip to content

Commit 9646dfb

Browse files
authored
Merge pull request #33 from oslabs-beta/dev
Merging in 3rd Party API compatibility feature
2 parents 4fb63d8 + 8b9f1e6 commit 9646dfb

6 files changed

+71
-35
lines changed

package-lock.json

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"description": "Welcome to a new era of GraphQL API development.",
55
"icon": "DOCUMENTATION/graphquill-logo.png",
66
"publisher": "sproutdeveloping",
7-
"version": "0.14.0",
7+
"version": "0.15.0",
88
"repository": {
99
"type": "git",
1010
"url": "https://github.com/oslabs-beta/GraphQuill.git"

src/extension.ts

+32-12
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,13 @@
88
* - updating variables in the event of changes in the config files
99
* @changelog : Austin Ruby, Nov. 15th: passed invocation of RFSRWR function within doc
1010
* save listener into debounce function to avoid overquerying API if user mashes save
11+
* @changelog : Austin Ruby, Nov. 22nd:
12+
* - added instructions for adding external server url to config file comments
13+
* - added logic to not invoke serverOn if using external server
14+
* - added logic to call RFSRWR if using external server
15+
* - added url argument to RFSRWR -- undefined if locally hosted server, otherwise
16+
* will be the url of the server
17+
* - accounted for external url on deactivation
1118
* * */
1219

1320
// eslint-disable-next-line import/no-unresolved
@@ -96,10 +103,11 @@ export function activate(context: vscode.ExtensionContext) {
96103
// Check ONCE if the port is open (also this does not need the third param)
97104
// will resolve to a true or false value
98105
const serverOnFromUser = await checkForRunningServer(portNumber, true);
99-
// console.log('--serverOnFromUser after once check is:', serverOnFromUser);
106+
const externalURL = entryPoint.slice(0, 4) === 'http';
100107

101108
// trigger serverOn if the user does not already have the server running
102-
if (!serverOnFromUser) {
109+
// AND if the server is not hosted at an external URL
110+
if (!serverOnFromUser && !externalURL) {
103111
// start up the user's server, pass in the gqChannel to log any error messages
104112
serverOn(entryPoint, gqChannel);
105113

@@ -133,16 +141,20 @@ export function activate(context: vscode.ExtensionContext) {
133141
}
134142
}
135143

136-
// if the server is on from either the user or graphquill, continue
137-
// send first query & setup on save listener
138-
if (serverOnFromUser || serverTurnedOnByGraphQuill) {
139-
// update isOnToggle (refers to state of GraphQuill extension running or not)
144+
// if the server is on from either the user or graphquill,
145+
// or the user is querying an external URL,
146+
// continue and send first query & setup on save listener
147+
if (serverOnFromUser || serverTurnedOnByGraphQuill || externalURL) {
148+
let url: (undefined|string);
149+
// if user's server is running at external url, set url to their specified entryPoint
150+
if (externalURL) url = entryPoint;
151+
// make isOnToggle true regardless of url to enable deactivation functionality
140152
isOnToggle = true;
141153

142154
// get the fileName of the open file when the extension is FIRST fired
143155
const currOpenEditorPath: string = vscode.window.activeTextEditor!.document.fileName;
144156
// send that request from the currentopeneditor
145-
readFileSendReqAndWriteResponse(currOpenEditorPath, gqChannel, portNumber, rootPath);
157+
readFileSendReqAndWriteResponse(currOpenEditorPath, gqChannel, portNumber, rootPath, url);
146158

147159

148160
const debouncedRFSRWR = debounce(
@@ -171,7 +183,7 @@ export function activate(context: vscode.ExtensionContext) {
171183
}
172184

173185
// send the filename and channel to the readFileSRAWR function
174-
debouncedRFSRWR(event.fileName, gqChannel, portNumber, rootPath);
186+
debouncedRFSRWR(event.fileName, gqChannel, portNumber, rootPath, url);
175187

176188
// satisfying linter
177189
return null;
@@ -193,6 +205,7 @@ export function activate(context: vscode.ExtensionContext) {
193205
// console.log('--deactivate functionality triggered');
194206

195207
// check isontoggle boolean
208+
// as long as user isn't querying external URL
196209
if (!isOnToggle) {
197210
// server is already off
198211
// console.log('server is already off');
@@ -261,7 +274,7 @@ export function activate(context: vscode.ExtensionContext) {
261274
// if it does not already exist, write to a new file
262275
fs.writeFileSync(graphQuillConfigPath,
263276
// string to populate the file with
264-
'module.exports = {\n // change "./server/index.js" to the relative path from the root directory to\n // the file that starts your server\n entry: \'./server/index.js\',\n\n // change 3000 to the port number that your server runs on\n portNumber: 3000,\n\n // to increase the amount of time allowed for the server to startup, add a time\n // in milliseconds (integer) to the "serverStartupTimeAllowed"\n // serverStartupTimeAllowed: 5000,\n};\n',
277+
'module.exports = {\n // change "./server/index.js" to the relative path from the root directory to\n // the file that starts your server.\n // if you\'re connecting to an external server,\n // change "./server/index.js" to its URL in the following format:\n // "https://yourserverurl.com"\n entry: \'./server/index.js\',\n\n // change 3000 to the port number that your server runs on\n portNumber: 3000,\n\n // to increase the amount of time allowed for the server to startup, add a time\n // in milliseconds (integer) to the "serverStartupTimeAllowed"\n // serverStartupTimeAllowed: 5000,\n};\n',
265278
'utf-8');
266279

267280
// open the file in vscode
@@ -276,6 +289,9 @@ export function activate(context: vscode.ExtensionContext) {
276289
// push it to the subscriptions
277290
context.subscriptions.push(disposableCreateConfigFile);
278291

292+
/** **************************************************************************
293+
* * Fifth GraphQuill option in command palette to SHOW THE SCHEMA
294+
************************************************************************** */
279295
const disposableShowGraphQLSchema = vscode.commands.registerCommand('extension.showGraphQLSchema', async () => {
280296
// console.log('show schema running');
281297
// show output channel, clear any old stuff off of it
@@ -300,11 +316,13 @@ export function activate(context: vscode.ExtensionContext) {
300316
// Check ONCE if the port is open (also this does not need the third param)
301317
// will resolve to a true or false value
302318
const serverOnAlready = await checkForRunningServer(portNumber, true);
319+
const externalURL = entryPoint.slice(0, 4) === 'http';
303320
// console.log('--serverOnFromUser after once check is:', serverOnFromUser);
304321
let serverTurnedOnBySchemaOutputter = false;
305322

306323
// trigger serverOn if the user does not already have the server running
307-
if (!serverOnAlready) {
324+
// or if user is requesting data from external server
325+
if (!serverOnAlready && !externalURL) {
308326
// start up the user's server, pass in the gqChannel to log any error messages
309327
serverOn(entryPoint, gqChannel);
310328

@@ -337,12 +355,14 @@ export function activate(context: vscode.ExtensionContext) {
337355
return setTimeout(() => serverOff(portNumber), 5000);
338356
}
339357
}
340-
358+
let url: (undefined|string);
359+
if (externalURL) url = entryPoint;
360+
// console.log('before invoking showSchema: ', url);
341361
// clear the channel off?
342362
gqChannel.clear();
343363

344364
// run required in functionality here, required in
345-
showGraphqlSchema(serverOnAlready, serverTurnedOnBySchemaOutputter, gqChannel, portNumber);
365+
showGraphqlSchema(serverOnAlready, serverTurnedOnBySchemaOutputter, gqChannel, portNumber, url);
346366

347367
// turn the server off if the extension turned it on
348368
// eslint-disable-next-line max-len

src/modules/client/parseConfigFile.ts

+7-3
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
* @function : return an object with the entryPoint and the allowServerTimeoutConfigSetting
99
* @param : none
1010
* @returns : an array with the root directory AND the entryPoint strings
11-
* @changelog : ##WHOEVER CHANGES THE FILE, date, details
11+
* @changelog : Austin Ruby, Nov. 22nd, 2019: added logic to not append rootpath to
12+
* entrypoint if entrypoint is external url
1213
* * */
1314

1415
// eslint-disable-next-line import/no-unresolved
@@ -35,8 +36,11 @@ function parseConfigFile(rootPath: string) {
3536
const configObject = require(`${gqConfigFilePath}`);
3637
// console.log('config object in parseconfigfile.ts', configObject);
3738

38-
// set the entry point to the absolute path (root + relative entry path)
39-
entryPoint = path.resolve(rootPath, configObject.entry);
39+
// if the entrypoint is an external url, set entryPoint to that url
40+
// otherwise set the entry point to the absolute path (root + relative entry path)
41+
entryPoint = configObject.entry.slice(0, 4) === 'http'
42+
? configObject.entry
43+
: path.resolve(rootPath, configObject.entry);
4044

4145
// set the portnumber
4246
portNumber = configObject.portNumber;

src/modules/client/readFileSendReqAndWriteResponse.ts

+9-4
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
* @changelog : Alex Chao, November 5th, 2019, merge conflict handling and server additions
1616
* @changelog : Alex Chao, November 6th, 2019, dynamic port number for fetching, coming from
1717
* the extension.ts file
18+
* @changelog : Austin Ruby, November 22nd, 2019, added url parameter to hold external server's
19+
* url or be undefined. if undefined, use localhost string with port from config file
1820
* * */
1921

2022
// eslint-disable-next-line import/no-unresolved
@@ -30,9 +32,14 @@ function readFileSendReqAndWriteResponse(
3032
channel: vscode.OutputChannel,
3133
portNumber: number,
3234
rootPath: string, // passing the root path in to control the function def. injection
35+
url: (undefined|string),
3336
) {
3437
// parse the contents of the entire filePath file to a string
3538
const copy = fs.readFileSync(filePath).toString();
39+
// if url is not undefined, user is querying external server
40+
// and url will be the correct url
41+
// otherwise use localhost with port number specified in config file
42+
const validatedURL: string = url || `http://localhost:${portNumber}/graphql`;
3643
// check if the file is within the root directory, otherwise we don't want to inject the
3744
// function defintion
3845
if (filePath.includes(rootPath) && !copy.includes('function graphQuill')) {
@@ -75,23 +82,22 @@ function readFileSendReqAndWriteResponse(
7582
// wrapping queries in Promise.all to ensure all fetches resolve before appending to channel
7683
const finalReqResObj = await Promise.all(
7784
// using map to generate array of promises
78-
queriesWithoutQuotes.map((reqResObj) => {
85+
queriesWithoutQuotes.map((reqResObj, index) => {
7986
// confirm object exists
8087
if (reqResObj) {
8188
// copy reqResObj to avoid mutating argument object
8289
const newReqResObj = { ...reqResObj };
8390
// destructure query off of object
8491
const { query } = newReqResObj;
8592
// using return here to return promise into Promise.all
86-
return fetch(`http://localhost:${portNumber}/graphql`, {
93+
return fetch(validatedURL, {
8794
method: 'POST',
8895
headers: { 'Content-Type': 'application/json' },
8996
body: JSON.stringify({ query }),
9097
})
9198
.then((response: Response) => response.json())
9299
// adding parsed API response to newReqResObject
93100
.then((parsedResponse: {data: Object, errors: Object}) => {
94-
// console.log('parsedResponse is: ', parsedResponse);
95101
newReqResObj.response = parsedResponse.data || parsedResponse.errors;
96102
return newReqResObj;
97103
})
@@ -105,7 +111,6 @@ function readFileSendReqAndWriteResponse(
105111
}),
106112
);
107113

108-
// console.log('finalReqResObj: ', finalReqResObj);
109114
channel.clear();
110115
channel.append('GraphQuill results:');
111116
channel.show(true);

src/modules/client/showGraphqlSchema.ts

+21-14
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
* @param : portNumber: number for the portnumber to send the introspection query to
88
* @returns : nothing
99
* @exports : the function that will append to the output channel when invoked
10-
* @changelog : ##WHOEVER CHANGES THE FILE, date, details
10+
* @changelog : Austin Ruby, Nov. 23rd, 2019: accounted for external urls
1111
* * */
1212

1313
/* eslint-disable no-unused-vars */
@@ -50,14 +50,15 @@ function schemaToStringQueryAndMutation(schemaPiece: any) {
5050
// remove the last comma of the arguments, place a closing paren
5151
queriesStr = queriesStr.slice(0, queriesStr.length - 2);
5252
if (one.args.length) queriesStr += '\n )';
53-
54-
// place the returned type at the end of the answer string
55-
if (one.type.ofType.kind !== 'LIST') {
56-
// if it's not a list, just put the type on the end, and an ! if it's non-nullable
57-
queriesStr += `: ${one.type.ofType.name}${one.type.kind === 'NON_NULL' ? '!' : ''}\n`;
58-
} else {
59-
// similar for a list but extra check for non-nullable elements as well
60-
queriesStr += `: [${one.type.ofType.ofType.ofType.name}${one.type.ofType.ofType === 'NON_NULL' ? '!' : ''}]${one.type.kind === 'NON_NULL' ? '!' : ''}\n`;
53+
if (one.type.ofType) {
54+
// place the returned type at the end of the answer string
55+
if (one.type.ofType.kind !== 'LIST') {
56+
// if it's not a list, just put the type on the end, and an ! if it's non-nullable
57+
queriesStr += `: ${one.type.ofType.name}${one.type.kind === 'NON_NULL' ? '!' : ''}\n`;
58+
} else {
59+
// similar for a list but extra check for non-nullable elements as well
60+
queriesStr += `: [${one.type.ofType.ofType.ofType.name}${one.type.ofType.ofType === 'NON_NULL' ? '!' : ''}]${one.type.kind === 'NON_NULL' ? '!' : ''}\n`;
61+
}
6162
}
6263
});
6364
return queriesStr;
@@ -101,12 +102,16 @@ async function showGraphqlSchema(
101102
serverTurnedOnByGraphQuill: boolean,
102103
gqChannel: vscode.OutputChannel,
103104
portNumber: number,
105+
url: (undefined|string),
104106
) {
107+
// if not using external url, send req to portNumber from config file
108+
const validatedURL = url || `http://localhost:${portNumber}/graphql`;
109+
console.log('validatedURL: ', validatedURL);
105110
// if the server is on from either the user or graphquill, continue
106111
// send the __schema query & setup on save listener
107-
if (serverOnFromUser || serverTurnedOnByGraphQuill) {
112+
if (serverOnFromUser || serverTurnedOnByGraphQuill || url) {
108113
// send that request ot get back the entire schema...
109-
const all = await fetch(`http://localhost:${portNumber}/graphql`, {
114+
const all = await fetch(validatedURL, {
110115
method: 'POST',
111116
headers: { 'Content-Type': 'application/json' },
112117
body: JSON.stringify({ // this beautiful string literal is the introspection query
@@ -174,7 +179,7 @@ async function showGraphqlSchema(
174179
}),
175180
}).then((res: Response) => res.json())
176181
.then((json: {data: {__schema: {types: Object[]}}}) => (
177-
// eslint-disable-next-line no-underscore-dangle
182+
// eslint-disable-next-line no-underscore-dangle
178183
json.data.__schema.types.filter((e: any) => ( // can't figure out this any...
179184
e.kind !== 'SCALAR')) // filter out the scalar types ('BOOLEAN', 'STRING')
180185
// this will cause problems for graphql apis that have custom scalar types... but mvp :)
@@ -189,8 +194,10 @@ async function showGraphqlSchema(
189194

190195
// same thing for the mutations
191196
const mutations = all.filter((e: {name: string}) => e.name === 'Mutation');
192-
const parsedMutations = schemaToStringQueryAndMutation(mutations);
193-
gqChannel.append(`\nMUTATIONS:\n${parsedMutations}\n`);
197+
if (mutations.length) {
198+
const parsedMutations = schemaToStringQueryAndMutation(mutations);
199+
gqChannel.append(`\nMUTATIONS:\n${parsedMutations}\n`);
200+
}
194201

195202
// almost the same thing for the types
196203
const types = all.filter((e: {name: string}) => e.name !== 'Mutation' && e.name !== 'Query' && e.name.slice(0, 2) !== '__');

0 commit comments

Comments
 (0)