Skip to content

Commit

Permalink
feat: add graph:init command (#4711)
Browse files Browse the repository at this point in the history
* feat: add graph:init command

* feat: add new command

* chore: update docs

* chore: address PR comments

* Apply suggestions from code review

Co-authored-by: Kyle Rollins <kyleblankrollins@gmail.com>

* fix: better error messages, and fix authentication

* fix: #4868

* chore: generate docs

Co-authored-by: Antonio Nuno Monteiro <anmonteiro@gmail.com>
Co-authored-by: Kyle Rollins <kyleblankrollins@gmail.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
  • Loading branch information
4 people authored Aug 1, 2022
1 parent 7203fe5 commit 22ac960
Show file tree
Hide file tree
Showing 11 changed files with 182 additions and 9 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ Manage netlify functions
| [`graph:config:write`](/docs/commands/graph.md#graphconfigwrite) | Write a .graphqlrc.json file to the current directory for use with local tooling (e.g. the graphql extension for vscode) |
| [`graph:edit`](/docs/commands/graph.md#graphedit) | Launch the browser to edit your local graph functions from Netlify |
| [`graph:handler`](/docs/commands/graph.md#graphhandler) | Generate a handler for a Graph operation given its name. See `graph:operations` for a list of operations. |
| [`graph:init`](/docs/commands/graph.md#graphinit) | Initialize all the resources for Netlify Graph |
| [`graph:library`](/docs/commands/graph.md#graphlibrary) | Generate the Graph function library |
| [`graph:operations`](/docs/commands/graph.md#graphoperations) | List all of the locally available operations |
| [`graph:pull`](/docs/commands/graph.md#graphpull) | Pull down your local Netlify Graph schema, and process pending Graph edit events |
Expand Down
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ Manage netlify functions
| [`graph:config:write`](/docs/commands/graph.md#graphconfigwrite) | Write a .graphqlrc.json file to the current directory for use with local tooling (e.g. the graphql extension for vscode) |
| [`graph:edit`](/docs/commands/graph.md#graphedit) | Launch the browser to edit your local graph functions from Netlify |
| [`graph:handler`](/docs/commands/graph.md#graphhandler) | Generate a handler for a Graph operation given its name. See `graph:operations` for a list of operations. |
| [`graph:init`](/docs/commands/graph.md#graphinit) | Initialize all the resources for Netlify Graph |
| [`graph:library`](/docs/commands/graph.md#graphlibrary) | Generate the Graph function library |
| [`graph:operations`](/docs/commands/graph.md#graphoperations) | List all of the locally available operations |
| [`graph:pull`](/docs/commands/graph.md#graphpull) | Pull down your local Netlify Graph schema, and process pending Graph edit events |
Expand Down
18 changes: 18 additions & 0 deletions docs/commands/graph.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ netlify graph
| [`graph:config:write`](/docs/commands/graph.md#graphconfigwrite) | Write a .graphqlrc.json file to the current directory for use with local tooling (e.g. the graphql extension for vscode) |
| [`graph:edit`](/docs/commands/graph.md#graphedit) | Launch the browser to edit your local graph functions from Netlify |
| [`graph:handler`](/docs/commands/graph.md#graphhandler) | Generate a handler for a Graph operation given its name. See `graph:operations` for a list of operations. |
| [`graph:init`](/docs/commands/graph.md#graphinit) | Initialize all the resources for Netlify Graph |
| [`graph:library`](/docs/commands/graph.md#graphlibrary) | Generate the Graph function library |
| [`graph:operations`](/docs/commands/graph.md#graphoperations) | List all of the locally available operations |
| [`graph:pull`](/docs/commands/graph.md#graphpull) | Pull down your local Netlify Graph schema, and process pending Graph edit events |
Expand Down Expand Up @@ -92,6 +93,23 @@ netlify graph:handler
- `httpProxy` (*string*) - Proxy server address to route requests through.
- `httpProxyCertificateFilename` (*string*) - Certificate file to use when connecting using a proxy server

---
## `graph:init`

Initialize all the resources for Netlify Graph

**Usage**

```bash
netlify graph:init
```

**Flags**

- `debug` (*boolean*) - Print debugging information
- `httpProxy` (*string*) - Proxy server address to route requests through.
- `httpProxyCertificateFilename` (*string*) - Certificate file to use when connecting using a proxy server

---
## `graph:library`

Expand Down
1 change: 1 addition & 0 deletions docs/commands/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ Manage netlify functions
| [`graph:config:write`](/docs/commands/graph.md#graphconfigwrite) | Write a .graphqlrc.json file to the current directory for use with local tooling (e.g. the graphql extension for vscode) |
| [`graph:edit`](/docs/commands/graph.md#graphedit) | Launch the browser to edit your local graph functions from Netlify |
| [`graph:handler`](/docs/commands/graph.md#graphhandler) | Generate a handler for a Graph operation given its name. See `graph:operations` for a list of operations. |
| [`graph:init`](/docs/commands/graph.md#graphinit) | Initialize all the resources for Netlify Graph |
| [`graph:library`](/docs/commands/graph.md#graphlibrary) | Generate the Graph function library |
| [`graph:operations`](/docs/commands/graph.md#graphoperations) | List all of the locally available operations |
| [`graph:pull`](/docs/commands/graph.md#graphpull) | Pull down your local Netlify Graph schema, and process pending Graph edit events |
Expand Down
14 changes: 7 additions & 7 deletions npm-shrinkwrap.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@
"multiparty": "^4.2.1",
"netlify": "^12.0.0",
"netlify-headers-parser": "^6.0.2",
"netlify-onegraph-internal": "0.4.0",
"netlify-onegraph-internal": "0.4.1",
"netlify-redirect-parser": "^13.0.5",
"netlify-redirector": "^0.2.1",
"node-fetch": "^2.6.0",
Expand Down
148 changes: 148 additions & 0 deletions src/commands/graph/graph-init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// @ts-check
const { Buffer } = require('buffer')

const { OneGraphClient } = require('netlify-onegraph-internal')
const { v4: uuidv4 } = require('uuid')

const { OneGraphCliClient, ensureCLISession } = require('../../lib/one-graph/cli-client')
const { NETLIFYDEVERR, chalk, error, exit, getToken, log } = require('../../utils')
const { msg } = require('../login/login')

const { ensureAppForSite, executeCreateApiTokenMutation } = OneGraphCliClient

/**
* Creates the `netlify graph:init` command
* @param {import('commander').OptionValues} options
* @param {import('../base-command').BaseCommand} command
* @returns
*/
const graphInit = async (options, command) => {
const { api, site, state } = command.netlify
const siteId = site.id

if (!siteId) {
error(
`${NETLIFYDEVERR} Warning: no siteId defined, unable to start Netlify Graph. To enable, run ${chalk.yellow(
'netlify init',
)} or ${chalk.yellow('netlify link')}`,
)
}

let [netlifyToken, loginLocation] = await getToken()
if (!netlifyToken) {
netlifyToken = await command.authenticate()
}

let siteData = null
try {
// @ts-ignore: we need better types for our api object
siteData = await api.getSite({ siteId })
} catch (error_) {
if (netlifyToken && error_.status === 401) {
log(`Already logged in ${msg(loginLocation)}`)
log()
log(`Run ${chalk.cyanBright('netlify status')} for account details`)
log()
log(`or run ${chalk.cyanBright('netlify switch')} to switch accounts`)
log()
log(`To see all available commands run: ${chalk.cyanBright('netlify help')}`)
log()
return exit()
}
throw error_
}

if (netlifyToken == null) {
error(
`${NETLIFYDEVERR} Error: Unable to start Netlify Graph without a login. To enable, run ${chalk.yellow(
'netlify login',
)} first`,
)
return exit()
}

await ensureAppForSite(netlifyToken, siteId)

await ensureCLISession({
metadata: {},
netlifyToken,
site,
state,
})

let envChanged = false

// Get current environment variables set in the UI
const {
build_settings: { env = {} },
} = siteData

const newEnv = {
...env,
}

if (!env.NETLIFY_GRAPH_WEBHOOK_SECRET) {
envChanged = true
const secret = Buffer.from(uuidv4()).toString('base64')
newEnv.NETLIFY_GRAPH_WEBHOOK_SECRET = secret
}

if (!env.NETLIFY_GRAPH_PERSIST_QUERY_TOKEN) {
const variables = {
input: {
appId: siteId,
scopes: ['MODIFY_SCHEMA', 'PERSIST_QUERY'],
},
}

const { jwt } = await OneGraphClient.getGraphJwtForSite({ siteId, nfToken: netlifyToken })
const result = await executeCreateApiTokenMutation(variables, {
siteId,
accessToken: jwt,
})

const token =
result.data &&
result.data.oneGraph &&
result.data.oneGraph.createApiToken &&
result.data.oneGraph.createApiToken.accessToken &&
result.data.oneGraph.createApiToken.accessToken.token

if (token) {
envChanged = true
newEnv.NETLIFY_GRAPH_PERSIST_QUERY_TOKEN = token
} else {
error(`Unable to create Netlify Graph persist query token: ${JSON.stringify(result.errors, null, 2)}`)
}
}

if (envChanged) {
// Apply environment variable updates
// @ts-ignore
await api.updateSite({
siteId,
body: {
build_settings: {
env: newEnv,
},
},
})

log(`Finished updating Graph-related environment variables for site ${siteData.name}`)
}
}

/**
* Creates the `netlify graph:init` command
* @param {import('../base-command').BaseCommand} program
* @returns
*/
const createGraphInitCommand = (program) =>
program
.command('graph:init')
.description('Initialize all the resources for Netlify Graph')
.action(async (options, command) => {
await graphInit(options, command)
})

module.exports = { createGraphInitCommand }
2 changes: 2 additions & 0 deletions src/commands/graph/graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
const { createGraphConfigWriteCommand } = require('./graph-config-write')
const { createGraphEditCommand } = require('./graph-edit')
const { createGraphHandlerCommand } = require('./graph-handler')
const { createGraphInitCommand } = require('./graph-init')
const { createGraphLibraryCommand } = require('./graph-library')
const { createGraphOperationsCommand } = require('./graph-operations')
const { createGraphPullCommand } = require('./graph-pull')
Expand All @@ -24,6 +25,7 @@ const createGraphCommand = (program) => {
createGraphConfigWriteCommand(program)
createGraphEditCommand(program)
createGraphHandlerCommand(program)
createGraphInitCommand(program)
createGraphLibraryCommand(program)
createGraphOperationsCommand(program)
createGraphPullCommand(program)
Expand Down
2 changes: 1 addition & 1 deletion src/commands/login/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,4 @@ Opens a web browser to acquire an OAuth token.`,
.option('--new', 'Login to new Netlify account')
.action(login)

module.exports = { createLoginCommand, login }
module.exports = { createLoginCommand, login, msg }
2 changes: 2 additions & 0 deletions tests/integration/snapshots/220.command.graph.test.js.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ Generated by [AVA](https://avajs.dev).
$ graph:config:write Write a .graphqlrc.json file to the current directory for use with local tooling (e.g. the graphql extension for vscode)␊
$ graph:edit Launch the browser to edit your local graph functions from Netlify␊
$ graph:handler Generate a handler for a Graph operation given its name. See \`graph:operations\` for a list of operations.␊
$ graph:init Initialize all the resources for Netlify Graph␊
$ graph:library Generate the Graph function library␊
$ graph:operations List all of the locally available operations␊
$ graph:pull Pull down your local Netlify Graph schema, and process pending Graph edit events␊
Expand Down Expand Up @@ -55,6 +56,7 @@ Generated by [AVA](https://avajs.dev).
$ graph:config:write Write a .graphqlrc.json file to the current directory for use with local tooling (e.g. the graphql extension for vscode)␊
$ graph:edit Launch the browser to edit your local graph functions from Netlify␊
$ graph:handler Generate a handler for a Graph operation given its name. See \`graph:operations\` for a list of operations.␊
$ graph:init Initialize all the resources for Netlify Graph␊
$ graph:library Generate the Graph function library␊
$ graph:operations List all of the locally available operations␊
$ graph:pull Pull down your local Netlify Graph schema, and process pending Graph edit events␊
Expand Down
Binary file modified tests/integration/snapshots/220.command.graph.test.js.snap
Binary file not shown.

1 comment on commit 22ac960

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📊 Benchmark results

Package size: 230 MB

Please sign in to comment.