所以,我已经为特定格式的json文件构建了这个解析器,将它们转换为GraphQL架构
import jsonToSchema from '../../helpers/json-to-schema.js';
import patientJson from './patient.json';
import valueSetJson from './value-set.json';
import relatedPersonJson from './related-person.json';
import practitionerJson from './practitioner.json';
import encounterJson from './encounter.json';
const patientInput = jsonToSchema(patientJson, true);
const patient = jsonToSchema(patientJson);
const valueSetInput = jsonToSchema(valueSetJson, true);
const valueSet = jsonToSchema(valueSetJson);
const relatedPersonInput = jsonToSchema(relatedPersonJson, true);
const relatedPerson = jsonToSchema(relatedPersonJson);
const practitionerInput = jsonToSchema(practitionerJson, true);
const practitioner = jsonToSchema(practitionerJson);
const encounterInput = jsonToSchema(encounterJson, true);
const encounter = jsonToSchema(encounterJson);
export {
patient,
patientInput,
valueSet,
valueSetInput,
relatedPerson,
relatedPersonInput,
practitionerInput,
practitioner,
encounterInput,
encounter
};
我有schema.js
这样的文件:
import { GraphQLObjectType, GraphQLSchema } from 'graphql';
import queries from './queries';
import mutations from './mutations';
export default new GraphQLSchema({
query: new GraphQLObjectType({ name: 'Query', fields: queries }),
mutation: new GraphQLObjectType({ name: 'Mutation', fields: mutations })
});
这个过程 - jsonToSchema
函数 - 有很多递归函数,随着项目变大,可能非常耗费资源。
所以,我想知道是否可以从这样的过程中获取结果模式,以便将模式的一个大对象作为字符串保存到.js
文件中
答案 0 :(得分:0)
所以,我已经使用fetch-graphql-schema npm包找到了解决方法。
第一个graphql server必须构建在远离解析器的模式中。
然后,我最终创建了一个gulp任务来保存架构 - 现在它被保存到.graphql
文件而不是.js
- 看起来像这样:
//the dev-server tasks starts the server in development mode
gulp.task('build-schema', ['dev-server'], function getSchema() {
fetchSchema(config.APP_URL + ':' + config.APP_PORT + '/' + config.GQL_URL_DIR, { readable: true })
.then(function(schema) {
fs.writeFile(path.join(__dirname, 'src/data/schema.graphql'), schema, function(err) {
if (err) {
return console.log(err);
}
console.log('Schema saved to: src/data/schema.graphql');
console.log('Closing server');
process.exit();
});
})
.catch(err => {
if (err.code === 'ECONNREFUSED') {
console.log('Server not loaded, retrying in one second....');
setTimeout(getSchema, 1000);
}
});
});
我的schema.js
看起来像这样:
import { GraphQLObjectType, GraphQLSchema } from 'graphql';
import schema from './schema.graphql';
import queries from './queries';
import mutations from './mutations';
import resolvers from '../data/resolvers.js';
import { addResolveFunctionsToSchema, makeExecutableSchema } from 'graphql-tools';
let gqlSchema;
if (process.env.NODE_ENV === 'production') {
gqlSchema = makeExecutableSchema({ typeDefs: schema, resolvers });
} else {
gqlSchema = new GraphQLSchema({
query: new GraphQLObjectType({ name: 'Query', fields: queries }),
mutation: new GraphQLObjectType({ name: 'Mutation', fields: mutations })
});
addResolveFunctionsToSchema(gqlSchema, resolvers);
}
export default gqlSchema;