xz8la8 / graphql-freestyle Goto Github PK
View Code? Open in Web Editor NEWgraphql-freestyle
License: MIT License
graphql-freestyle
License: MIT License
一直以来Javascript作为脚本语言为前端带来极大的便捷,数据转换就是一把梭,但其隐患也是非常多的,一个空引用就让我们欲哭无泪,Typescript的出现在很大程度上改善了这种状况,但前端还有一个最重要的部分就是后端服务请求,这些请求格式很多时候都是前后端商议的,或者一方决定,另一方follow,诚然这种方式简单高效,但“口头约定”本身就缺乏效用,开发阶段前后端因为某个接口字段格式的争吵时常发生,那如何把“口头约定”变成一种受“法律保护的合同”呢,那首先就要有一个严格的条款(标准),那么GraphQL从某种程度就给出了这样一个条款。
很多人认为 GraphQL 是一个强类型查询语言,参数与返回结果都必须限定类型。例如客户端需要查询一个Person的信息,那参数id就必须是Int且必填,返回结果必须返回Person类型,否则浏览器就会认为是非法查询,不做返回。
这种强类型从何而来呢,答案就是Schema,GraphQL与RestAPI最大的不同就是,GraphQL为应用服务的接口提供了一套定义所有参数、返回结果类型的Schema。
GraphQL提供了5种基本数据类型,
GraphQL支持使用基本类型来组装复合数据类型(Composite Data Type),例如
type Person {
id: ID,
name: String,
department: String
male: Boolean
}
`
enum Gender {
male
female
}
`
列表(数组)可以使用[type]来表示,例如字符串列表就可以表示为[String],复合类型列表可以使用[Person]表示。
数据类型有了,那如何去操作这些数据呢,下面我们以一个经典的Teacher和Student为例来讲解。
Teacher 数据类型
type Teacher {
id: ID!
name: String
gender: Gender
students: [Students]
}
Student 数据类型
type Student {
id: ID!
name: String
gender: Gender
}
GraphQL预设了三种特殊的数据类型:
GraphQL约定必须提供一个query入口,
type Query {
allTeachers: [Teacher]
teacher(id: ID!): Teacher
}
schema {
query: Query
}
那么如何使用以上查询操作呢,
查询所有老师
query {
allTeachers {
id
name
}
}
根据id查询某个老师
query {
teacher(id: '1001') {
id
gender
}
}
或者
query queryTeacherById($id: !ID){
teacher(id: $id) {
id
gender
}
}
variables: {
id: '1001'
}
例如某个老师新招了一个学生,
type Mutation {
recruitStudent(id: ID!, name: String): Student
}
schema {
query: Query
mutation: Mutation
}
那么如何使用以上修改操作呢,
mutation {
recruitStudent(id: '1001-02', name: '小A') {
id
name
gender
}
}
本篇介绍了GraphQL的基础,也是最为关键的部分之一,下一篇将在这篇基础之上讲解更多类型的定义方式,并完成一个老师学生的CRUD示例。
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.