[关闭]
@duanyubin 2017-05-24T07:28:02.000000Z 字数 1499 阅读 235

GraphQL

NODE


Category

  1. GraphQL
  2. jsonwebtoken
  3. redux server render
  4. HOC && recompose

What is GraphQL

1. A query language for your API

GraphQL provides a complete and understandable description of the data in your API

3. Get exactly what you need

  1. // before
  2. {
  3. person {
  4. name
  5. email
  6. }
  7. }
  8. // data
  9. {
  10. "person": {
  11. "name": "ybduan",
  12. "email": "ybduan@corp.netease.com"
  13. }
  14. }
  15. // after
  16. {
  17. person {
  18. name
  19. }
  20. }
  21. // data
  22. {
  23. "person": {
  24. "name": "ybduan"
  25. }
  26. }

4. Get many resources in a single request

  1. // query
  2. {
  3. person {
  4. name
  5. posts {
  6. title
  7. }
  8. }
  9. }
  10. // result
  11. {
  12. "person": {
  13. "name": "ybduan",
  14. "posts": [{
  15. "title": "This is title"
  16. }, {
  17. "title": "This is another title"
  18. }]
  19. }
  20. }

5. Type system

  1. // query
  2. {
  3. person {
  4. name
  5. posts {
  6. title
  7. }
  8. }
  9. }
  10. //
  11. type person {
  12. name: String!
  13. email: String
  14. posts: [Post]
  15. }
  16. type Post {
  17. title: String
  18. content: String
  19. }

6. No versions

Add new fields and types to your GraphQL API without impacting existing queries

How to do

1. Describe your data

  1. // Define type
  2. type Person {
  3. name: String
  4. email: String
  5. posts: [Post]
  6. }
  7. type Query {
  8. person(name: String): Person
  9. }
  10. // Define resolver
  11. const resolverFunctions = {
  12. Query: {
  13. async person(_, args, context) {
  14. return await DB.model('person').find({ where: { name: args.name })
  15. }
  16. },
  17. Person: {
  18. async posts(person, args, context) {
  19. return await person.getPosts()
  20. }
  21. }
  22. }

2. Ask for what you want

  1. {
  2. person(name: "ybduan") {
  3. email
  4. }
  5. }

3. Get predictable results

  1. {
  2. "person": {
  3. "email": "ybduan@corp.netease.com"
  4. }
  5. }

Troubleshootings

Business Logic Layer

Where to perform validation and authorization checks

layer

Authorization

  1. const resolveFunctions = {
  2. Person: {
  3. posts(person, args, context = {}) {
  4. // return person.getPosts()
  5. const where = (context.authToken && person.id === context.authToken.id) ? null : { outward: true }
  6. return person.getPosts({ where }).then((data) => {
  7. return data
  8. })
  9. }
  10. }
  11. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注