allow exporting async functions as databases in json2graphql (#1543)

This commit is contained in:
Darío Javier Cravero 2019-02-01 11:34:36 +00:00 committed by Aravind Shankar
parent 68da491d9d
commit 5739b75000
3 changed files with 51 additions and 2 deletions

View File

@ -202,6 +202,21 @@ module.exports = {
}; };
``` ```
If you need to do some asynchronous stuff before exporting your data, you can
also export an function:
*Note: You can require [node-fetch](https://www.npmjs.com/package/node-fetch) in your function*
```js
const fetch = require('node-fetch');
module.exports = async function() {
const db = await fetch (...)
return db
}
```
## Use cases ## Use cases
### Play with GraphQL on your MongoDB data ### Play with GraphQL on your MongoDB data

View File

@ -0,0 +1,33 @@
const fetch = require('node-fetch');
const db = async () => {
const response = await fetch(
'https://bazookaand.herokuapp.com/v1alpha1/graphql',
{
method: 'POST',
headers: {
'x-hasura-access-key': 'advancedbitch'
},
body: JSON.stringify({
query: `
query {
items {
id
item
order_id
}
users {
id
name
balance
}
}
`,
})
}
);
const respObj = await response.json();
return respObj.data;
}
module.exports = db;

View File

@ -23,7 +23,7 @@ class JSON2GraphQL extends Command {
if (!db) { if (!db) {
throw new CLIError('path to sample database is required: \'json2graphql <url> -d ./db.js\''); throw new CLIError('path to sample database is required: \'json2graphql <url> -d ./db.js\'');
} }
const dbJson = this.getDbJson(db); const dbJson = await this.getDbJson(db);
const headers = key ? {'x-hasura-access-key': key} : {}; const headers = key ? {'x-hasura-access-key': key} : {};
const urlVerification = await this.verifyUrl(safeUrl, headers); const urlVerification = await this.verifyUrl(safeUrl, headers);
if (urlVerification.error) { if (urlVerification.error) {
@ -35,7 +35,8 @@ class JSON2GraphQL extends Command {
} }
getDbJson(db) { getDbJson(db) {
return require(resolve(db)); const ret = require(resolve(db));
return typeof ret === 'function' ? ret() : ret;
} }
getSafeUrl(url) { getSafeUrl(url) {