【发布时间】:2018-01-05 12:16:57
【问题描述】:
我正在为新的全栈项目采用 GraphQL,并且我已经研究了许多概念并开始了我的第一个项目。
我的问题与使用声明式与编程式 GraphQL 架构定义有关。基本上我在GraphQL official site 中看到的所有内容都使用声明性方法:您在一个或多个文件中定义架构,例如(感谢this example here):
type Brand {
name: String
logoUrl: String
}
enum Gender {
MALE
FEMALE
}
type Image {
thumbnailUrl: String
smallUrl: String
mediumUrl: String
largeUrl: String
}
type Article {
id: ID! # non-nullable, is guaranteed to exist on every article
name: String
thumbnailUrl: String
brand: Brand
genders: [Gender]
images: [Image]
recommendations: [Article]
}
type Query {
Article(id: ID!): Article
Articles: [Articles]
}
即使对于某种复杂的数据结构,代码也非常干净简洁。
但我在网络上看到的大多数示例,甚至在我研究过的书籍上都使用编程方法来构建架构,例如:
import { GraphQLObjectType, GraphQLInputObjectType } from 'graphql';
import {GraphQLNonNull, GraphQLID, GraphQLList } from 'graphql';
import { GraphQLString, GraphQLInt, GraphQLBoolean } from 'graphql';
import { UserType } from '../User/types';
import UserModel from '../../../models/User';
const fields = {
_id: {
type: new GraphQLNonNull(GraphQLID)
},
name: {
type: GraphQLString
},
phone: {
type: GraphQLString
}
};
const CompanyType = new GraphQLObjectType({
name: 'Company',
description: 'Company',
fields: fields
})
const Company = {
type: CompanyType,
description: 'Get single company',
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLID)
}
},
resolve(root, params) {
params.deleted = false;
return CompanyModel.find(params).exec();
}
}
const Companies = {
type: new GraphQLList(CompanyType),
description: 'Get all companies',
resolve(root) {
const companies = CompanyModel.find({ deleted: false }).exec();
if (!companies) {
throw new Error('Error getting companies.')
}
return companies;
}
}
export default {
Company,
Companies
}
我的目标是构建一个大型 SaaS 应用程序,因此架构会变得非常复杂,我担心代码很快就会变得复杂。
那么,我应该采用声明式方法、程序式方法还是两者的混合?
这里的最佳做法是什么?
【问题讨论】:
标签: javascript graphql