[relay-compiler] using __generated__ relay queries of shared module
We have a backend ruby API/graphql engine, as well as a shared UI module that are reused in different applications (both server and client side). Each client side app customizes the use and expands upon the ui module.
In the following case, our dummy client side app (used for testing the engine) uses the ui module which has the majority of the UI widgets and therefore relay code (from dummy/src/routes.js):
// @flow
import React from 'react'
import Route, {makeRouteConfig} from 'found'
import AppFrame from '@alienfast/ui/App/AppFrame'
import {graphql} from 'react-relay'
export default makeRouteConfig (
<Route
component={AppFrame}
query={graphql`
query routes_DummyApp_Query {
current_user {
...AppFrame_currentUser
}
}`
}
/>
)
Error:
Command failed `relay-compiler --src ./src --schema ./schema.json`:
Invariant Violation: RelayApplyFragmentArgumentTransform: expected `AppFrame_currentUser` to be a fragment, got `undefined`.
at invariant (/Users/kross/projects/af/spec/dummy/ui/node_modules/fbjs/lib/invariant.js:44:15)
at transformFragmentSpread (/Users/kross/projects/af/spec/dummy/ui/node_modules/relay-compiler/bin/relay-compiler:4874:26)
at /Users/kross/projects/af/spec/dummy/ui/node_modules/relay-compiler/bin/relay-compiler:4936:24
at Array.forEach (native)
at transformSelections (/Users/kross/projects/af/spec/dummy/ui/node_modules/relay-compiler/bin/relay-compiler:4931:15)
at transformField (/Users/kross/projects/af/spec/dummy/ui/node_modules/relay-compiler/bin/relay-compiler:4890:23)
at /Users/kross/projects/af/spec/dummy/ui/node_modules/relay-compiler/bin/relay-compiler:4946:24
at Array.forEach (native)
at transformSelections (/Users/kross/projects/af/spec/dummy/ui/node_modules/relay-compiler/bin/relay-compiler:4931:15)
at transformNode (/Users/kross/projects/af/spec/dummy/ui/node_modules/relay-compiler/bin/relay-compiler:4854:21)
Other links:
- #1790
- My SO question
How can we reuse queries that are not in the source tree but contained in our shared module?
Ok, so after some hacking on RelayCompilerBin and much tracing of code, I think I have a non-cleaned up hack working:
const parserConfigs = {
'@alienfast/ui': {
baseDir: '/Users/kross/projects/ui/src',
getFileFilter: RelayFileIRParser.getFileFilter,
getParser: RelayFileIRParser.getParser,
getSchema: () => getSchema(schemaPath),
watchmanExpression: buildWatchExpression(options)
},
default: {
baseDir: srcDir,
getFileFilter: RelayFileIRParser.getFileFilter,
getParser: RelayFileIRParser.getParser,
getSchema: () => getSchema(schemaPath),
watchmanExpression: buildWatchExpression(options)
}
}
const writerConfigs = {
default: {
getWriter: getRelayFileWriter(srcDir),
parser: 'default',
baseParsers: ['@alienfast/ui'] // Add shared module documents
}
}
The gist is that you need to define additional parserConfigs keys to capture existing generated files, and you need to tell the writerConfigs['default'] about the baseParsers, so that it can use the documents/fragments found in the baseParsers to generate for the current project.
Is there an easier way to do this? Am I on the right track? If so, perhaps we could enhance RelayCompilerBin and parameterize the extra modules to harvest documents from?
You need to re-parse original source with graphql tags using ^^^ method.
Since I have *.js.flow shadow files exported with my lib, I can parse these files from node_modules (requires the proper watchman expressions).
One problem with this approach is the re-parsing of *.js.flow files is broken, I'll be submitting a fix for that resolution.
This is a custom bin file/compiler that relies upon the master plus PR #1901. We have some utility code in here from our own source e.g. log, but nothing else of substance missing. It uses the *.js.flow shadow files included with my lib to obtain the baseDocuments.
bin/relayCompile.js:
#!/usr/bin/env node
// @flow
import RelayCompiler from '../RelayCompiler'
import yargs from 'yargs'
// Collect args
const argv = yargs
.usage(
'Create Relay generated files\n\n' +
'$0 [--schema, --src, --modules, --watch, --extensions]'
)
.options({
schema: {
default: './schema.json',
describe: 'Path to schema.graphql or schema.json',
type: 'string'
},
src: {
default: './src',
describe: 'Root directory of application code',
type: 'string'
},
modules: {
describe: 'Modules used as base documents (--modules foo bar)',
array: true,
type: 'string'
},
watch: {
describe: 'If specified, watches files and regenerates on changes',
type: 'boolean'
}
})
.help().argv
const rc = new RelayCompiler({
debug: false,
runConfig: argv
})
rc.compile()
RelayCompiler.js:
// @flow
import BaseShell from './BaseShell'
import KnifeWrench from './KnifeWrench'
import merge from 'lodash/merge'
import type {BaseShellConfig, BaseShellOptions, ShellResult} from './BaseShell'
import {find} from './exec'
import RelayCodegenRunner from '@alienfast/relay-compiler/lib/RelayCodegenRunner'
import RelayFileIRParser from '@alienfast/relay-compiler/lib/RelayFileIRParser'
import RelayFileWriter from '@alienfast/relay-compiler/lib/RelayFileWriter'
import RelayIRTransforms from '@alienfast/relay-compiler/lib/RelayIRTransforms'
import formatGeneratedModule from '@alienfast/relay-compiler/lib/formatGeneratedModule'
import File from './File'
import fs from 'fs'
import path from 'path'
import resolve from 'resolve'
import {
buildASTSchema,
buildClientSchema,
parse,
printSchema
} from 'graphql'
import type {GraphQLSchema} from 'graphql'
const {
codegenTransforms,
fragmentTransforms,
printTransforms,
queryTransforms,
schemaExtensions
} = RelayIRTransforms
// Ensure that a watchman "root" file exists in the given directory or a parent so that it can be watched
const WATCHMAN_ROOT_FILES = [ '.git', '.hg', '.watchmanconfig' ]
function hasWatchmanRootFile (testPath) {
while (path.dirname(testPath) !== testPath) {
if (
WATCHMAN_ROOT_FILES.some(file => {
return fs.existsSync(path.join(testPath, file))
})
) {
return true
}
testPath = path.dirname(testPath)
}
return false
}
function buildWatchExpression (extensions: Array<string>) {
return [
'allof',
[ 'type', 'f' ],
[ 'anyof', ...extensions.map(ext => [ 'suffix', ext ]) ],
[ 'not', [ 'match', '**/node_modules/**', 'wholename' ] ],
[ 'not', [ 'match', '**/__mocks__/**', 'wholename' ] ],
[ 'not', [ 'match', '**/__tests__/**', 'wholename' ] ],
[ 'not', [ 'match', '**/__generated__/**', 'wholename' ] ],
[ 'not', [ 'match', 'flow/**', 'wholename' ] ], // do not match root flow dir
[ 'not', [ 'match', 'flow-typed/**', 'wholename' ] ] // do not match root flow-typed dir
]
}
function getRelayFileWriter (baseDir: string) {
return (onlyValidate, schema, documents, baseDocuments) =>
new RelayFileWriter({
config: {
formatModule: formatGeneratedModule,
compilerTransforms: {
codegenTransforms,
fragmentTransforms,
printTransforms,
queryTransforms
},
baseDir,
schemaExtensions
},
onlyValidate,
schema,
baseDocuments,
documents
})
}
function getSchema (schemaPath: string): GraphQLSchema {
try {
let source = fs.readFileSync(schemaPath, 'utf8')
if (path.extname(schemaPath) === '.json') {
source = printSchema(buildClientSchema(JSON.parse(source).data))
}
source = `
directive @include(if: Boolean) on FRAGMENT | FIELD
directive @skip(if: Boolean) on FRAGMENT | FIELD
${source}
`
return buildASTSchema(parse(source))
} catch (error) {
throw new Error(
`
Error loading schema. Expected the schema to be a .graphql or a .json
file, describing your GraphQL server's API. Error detail:
${error.stack}
`.trim()
)
}
}
type RunOptions = {
schema: string,
src: string,
modules?: Array<string>,
watch?: ?boolean
}
type Options = {
...$Exact<BaseShellOptions>,
runConfig: RunOptions
}
type Config = {
...$Exact<BaseShellConfig>,
runConfig: RunOptions
}
/**
* "relay": "relay-compiler --src ./src --schema ./schema.json",
*/
class RelayCompiler extends BaseShell<Options, Config> {
knifeWrench: KnifeWrench
path: string
constructor (options?: Options) {
super(merge({}, options))
this.knifeWrench = new KnifeWrench(merge({}, options))
}
isSuccessful (shellResult: ShellResult) {
return shellResult.code === 0 // strict
}
compile () {
const { git } = this.knifeWrench
// generate new ones
// const args = resolveArgs('--src ./src --schema ./schema.json')
// this.exec(`${this.path} ${args.join(' ')}`)
this.run(this.config.runConfig).catch(error => {
this.log.error(String(error.stack || error))
process.exit(1)
})
if (this.knifeWrench.isCI()) {
// if we actually generated new files, we need to commit
const diff = git.diff(false)
if (diff) {
this.knifeWrench.setupCommitter()
git.add('') // git add -A stages all included deleted
git.commit(`Relay compiled [skip ci]`)
// cannot push here?
}
}
}
async run (options: RunOptions) {
const schemaPath = path.resolve(process.cwd(), options.schema)
if (!File.exists(schemaPath)) {
throw new Error(`schema path does not exist: ${schemaPath}.`)
}
const srcDir = path.resolve(process.cwd(), options.src)
if (!File.exists(srcDir)) {
throw new Error(`src path does not exist: ${srcDir}.`)
}
if (options.watch && !hasWatchmanRootFile(srcDir)) {
throw new Error(
`
watch requires that the src directory have a valid watchman "root" file.
Root files can include:
- A .git/ Git folder
- A .hg/ Mercurial folder
- A .watchmanconfig file
Ensure that one such file exists in ${srcDir} or its parents.
`.trim()
)
}
const parserConfigs: { [key: string]: any } = {}
// create parser configs for all modules
if (options.modules) {
options.modules.forEach((module) => {
let modulePath = resolve.sync(module, {
basedir: process.cwd(),
extensions: [ '.js', '.json' ]
})
// get only the module path source dir (not /index.js)
if (modulePath) {
modulePath = path.dirname(modulePath)
}
this.log.debug(`Resolved module: ${module} to ${modulePath}`)
if (!File.exists(modulePath)) {
throw new Error(`Module path does not exist: ${modulePath}.`)
}
parserConfigs[ module ] = {
getFileFilter: RelayFileIRParser.getFileFilter,
getParser: RelayFileIRParser.getParser,
getSchema: () => getSchema(schemaPath),
watchmanExpression: buildWatchExpression([ 'js.flow' ]),
baseDir: modulePath
}
})
}
// Get module keys as `baseParsers`
const baseParsers = Object.keys(parserConfigs)
// Finally add our srcDir as 'default'
parserConfigs[ options.src ] = {
getFileFilter: RelayFileIRParser.getFileFilter,
getParser: RelayFileIRParser.getParser,
getSchema: () => getSchema(schemaPath),
watchmanExpression: buildWatchExpression([ 'js' ]),
baseDir: srcDir
}
//this.log.debug(`parserConfigs`)
//this.log.dump(parserConfigs)
const writerConfigs = {
[options.src]: {
getWriter: getRelayFileWriter(srcDir),
parser: options.src,
baseParsers // Add shared module documents
}
}
this.log.debug(`writerConfigs`)
this.log.dump(writerConfigs)
this.log.info(`Generating in ${options.src} with shared queries from [${baseParsers.join(', ')}]`)
const codegenRunner = new RelayCodegenRunner({
parserConfigs,
writerConfigs,
onlyValidate: false,
skipPersist: true
})
if (options.watch) {
await codegenRunner.watchAll()
} else {
console.log('HINT: pass --watch to keep watching for changes.')
await codegenRunner.compileAll()
}
}
}
export default RelayCompiler
Some of this code could be reincorporated to the existing RelayCompileBin.js if there are others looking for this on a regular basis. Primarily, the resolution of parserConfigs with the exposed --modules option is the difference.
There appears to be support for shared modules in 1.2.0-rc1 and greater from 94c8b203a95b1366b4034459d1c594e092de92ee
#1921 duplicates this issue
for anyone stumbling upon this issue in the future, as of [email protected], you can create a config like this:
// lives at <rootDir>/scripts/relayCompiler.js
const spawn = require('child_process').spawn;
const path = require('path');
const args = [
'--extensions',
'js',
'jsx',
'--schema',
path.resolve(__dirname, '../data/graphql.schema.json'), // or wherever you store your schema file
'--src',
path.resolve(__dirname, '..'), // since we are currently in <rootDir>/scripts
'--include', // these will be based off of the `--src` flag ☝️
'src/**',
'storybook/**',
'node_modules/shared-component/src/**', // your node modules you want to compile
'--exclude',
'**/__mocks__/**',
'**/__tests__/**',
'**/__generated__/**'
];
if (process.argv.includes('--watch')) {
args.push('--watch');
}
if (process.argv.includes('--no-watchman')) {
// use this flag if linking node modules
args.push('--no-watchman');
}
const proc = spawn(
path.resolve(__dirname, '../node_modules/.bin/relay-compiler'),
args,
{stdio: 'inherit'}
);
proc.on('close', code => {
process.exit(code);
});
We ran into similar issues at work and the initial solution was similar to what @rosskevin did with taking the entire RelayCompiler.js file and reimplementing it into our project. Since [email protected], the --include and --exclude flags (listed in the const args array above) landed allowing you, well, include and exclude different files to compile and not compile.
In your package.json you can add this simple script now:
"scripts": {
"relay": "node scripts/relayCompiler.js"
}