在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):victorteokw/graphql-joker开源软件地址(OpenSource Url):https://github.com/victorteokw/graphql-joker开源编程语言(OpenSource Language):JavaScript 75.6%开源软件介绍(OpenSource Introduction):GraphQL JokerGraphQL Joker is the ultimate GraphQL scaffolding tool. It automates coding process to save your precious time, enhance your work and life experience. In other words, GraphQL Joker write code for you with commands you specified. With GraphQL Joker, you can create a full-fledged backend server with your complex app logic and running API in less than 3 minutes. Documentation
MotivationWhen working on GraphQL projects, we need to define database schema and GraphQL twice. We need to create resolvers for the standardized API. A lot of copying and pasting are going on. It's not elegant to copy code around and find-replace all occurrences. It's also error prone. And sometimes causing unnoticeable errors which wastes time. Wouldn't be nice if we could have a tool just like Ruby on Rails' scaffold tool to generate code for us? Design ConceptGraphQL Joker is designed to provide features at least Ruby on Rails scaffold tool has. Aka, generate boilerplate business logic code as much as possible for you. However, unlike Ruby on Rails, GraphQL Joker is not a full-fledged framework and will never provide a framework for you. It focus on business logic generation. Although GraphQL Joker also has project generation feature, it's trying to hook up the industry standard and battle-tested libraries and components together for you. And it's configurable. To split features into small core chunks and make them combinable and adaptable is a good practice and especially popular in node.js ecosystem, GraphQL Joker embraces this practice. That's what makes GraphQL Joker outstanding and what makes GraphQL Joker really a flexible and configurable scaffolding tool. InstallationGraphQL Joker is a general command line tool, thus you should install it globally. npm install -g graphql-joker Create an GraphQL ProjectTo create an GraphQL project, use joker app my-new-app This will generate your app in 'my-new-app' folder. If you don't specify app name, the app will be created at your current working directory. Options:
To change default eslint config being used: joker app my-new-app --eslint-config=your-config To automatically run joker app my-new-app --git-init Generate ResourcesAPI resource generation is the core feature of GraphQL Joker. It's syntax is rather simple and extensible. It follows this basic style: joker resource ModelName[/optionalPluralVariableName] \
primitiveField[[:Type[typeModifiers]]:defaultValue]... \
referenceField[[:ReferenceType[typeModifiers]]:foreignKey]... This arguments specification is obscure to see. Let's see some examples. Let's say you have a model named user, and user has a name, an age and also a list of posts. And you have a model named post, it has title, content and author. Just type like this: joker resource User name:String age:Int posts:[Post]:author
joker resource Post title:String content:String author:User Here we specified our first model 'User', with following fields:
We defined our second model named 'Post', with following fields:
This creates six files in total, three for User and three for Post. The three files are mongoose model, GraphQL schema and GraphQL resolver. The autogenerated models/User.js looks like this: const mongoose = require('mongoose');
const { Schema } = mongoose;
const userSchema = new Schema({
name: String,
age: Number
}, {
timestamps: true,
collection: 'users'
});
module.exports = mongoose.model('User', userSchema); The autogenerated schemas/User.gql looks like this: type User {
_id: ID!
name: String
age: Int
posts: [Post]
createdAt: Date
updatedAt: Date
}
input UserInput {
name: String
age: Int
}
type Query {
user(_id: ID!): User
users: [User]
}
type Mutation {
createUser(input: UserInput): User
updateUser(_id: ID!, input: UserInput): User
deleteUser(_id: ID!): User
} The autogenerated resolvers/User.js looks like this: module.exports = {
User: {
async posts(root, _, { Post }) {
return await Post.find({ author: root._id });
}
},
Query: {
async user(root, { _id }, { User }) {
return await User.findById(_id);
},
async users(root, { _ }, { User }) {
return await User.find();
}
},
Mutation: {
async createUser(root, { input }, { User }) {
return await User.create(input);
},
async updateUser(root, { _id, input }, { User }) {
return await (await User.findById(_id)).set(input).save();
},
async deleteUser(root, { _id }, { User }) {
return await (await User.findById(_id)).remove();
}
}
}; Besides your schema definition, 5 API are created for you. Those are:
Now you can CRUD your resources through API. Primitive TypesGraphQL Joker supports a wide range of primitive types:
When you are defining a field with type mentioned above, GraphQL Joker will treat them as primitive types. When you refer to a type that is not included in the list, GraphQL Joker will treat it as a referecing to another model. joker resource User disabled:Boolean name:String description:Mixed spouse:User In the above example, obviously Array TypeSurround a type with a pair of [], you get an array of that type, for example:
The field Reference TypesThere are several ways to implement your own reference types. one-to-oneThe simplest case is one-to-one relation ship. joker resource User address:Address
joker resource Address user:User:address In this case, we save the reference into user model, and on address model, we use the foreign key on user model to fetch the user value. one-to-manyWe have two ways to implement this relationship. joker resource User posts:[Post]:owner
joker resource Post user:User:owner This is the most common case. We save the reference on the 'many' side, and fetch on the 'many' side model. joker resource User posts:[Post]
joker resource Post user:User:[posts] In this case, we are saving the references on the 'one' side, and on 'many' side, we use a pair of [] to indicate it's an array. Be careful of performance when you are doing this way. many-to-manyIn simple cases, we can just do like this. joker resource User courses:[Course]
joker resource Course users:[User]:[courses] If there are tons of records, then you may want to use association table. joker resource Favorite user:User course:Course
joker resource User courses:[Course]:Favorite
joker resource Course users:[User]:Favorite In this case, we specified a relationship that is have many ... through ... Upload TypeTo create an uploading field, use joker resource User avatar:AvatarUploader To create an uploader, see Generate Uploader Type ModifiersIn the real world practices, fields should be validated. For example, You may want a user's email to match designated format and to be required and unique. You can specify type modifiers. joker resource User 'email:String/.*@.*\..*/!$' In the above example, Existing type modifiers includes:
Default ValuesYou can specify default value to a primitive field with the following syntax. joker resource Post 'title:String!:Untitled' 'lastUpdate:Date!:`Date.now`' Here, title's default value is Nested StructureTo create nested structure, use the following syntax: joker resource User posts:[{ title:String content:String comments:[{ \
commenter:User content:String }] }] email:String password:String settings:{ \
sms:Boolean email:Boolean pushNotification:Boolean } Specify type as EnumsTo create enum fields, use enum syntax like this: joker resource User 'gender:Enum(male,female)!' Reusable NestablesGraphQL Joker supports reusable nestables and referencing them. joker nestable Address line1:String line2:String country:String region:String
joker resource User address:addressSchema name:String Specify the lowercase nestable name append by 'Schema', joker will treat the type as a subschema reference. Destroy ResourcesIf you mistakenly generated something or you spell something wrongly, use the 'destroy' command to delete the autogenerated files. Just append destroy with the original command, it automatically destroys the generated content. joker destroy resource User name:String Generate UploaderTo generate an uploader, use joker uploader FileUploader extends AliOSSUploader bucket=your-bucket-name region=your-region This generates an base file uploader for you. Integrate with Existing ProjectGraphQL Joker is designed to be a generic tool. It does not require a project to be a GraphQL Joker project. Customize GraphQL Joker BehaviorCreate a file called {
"schemaDir": "graphql",
"resolverDir": "graphql",
"test": false
} GraphQL Joker will generate schema files and resolver files into graphql directory, and will not generate unit tests. Issues and HelpsGraphQL Joker is not mature yet. If you find anything uncomfortable or confuses you. Any discuss, issue and pull request are welcome. RoadmapGraphQL Joker is an ambitious project and it still has a long way to go.
LicenseThe GNU General Public License v3.0. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论