1. Why we moving API from REST to Graphql?
2. What is Graphql?
3. Graphql in Golang (Why we choose Golang)
4. How to testing Graphql in Golang
5. Deploy Graphql application
AGENDA ▸ Why we moving API from REST to Graphql? ▸ What is Graphql? ▸ Graphql in Golang (Why we choose Golang) ▸ How to testing Graphql in Golang ▸ Deploy Graphql application
/** * @api {get} /scene/:id Request Scene information * @apiName GetScene * @apiGroup Scene * * @apiParam {Number} id Scenes unique ID. * * @apiSuccess {String} title Title of the Scene. * @apiSuccess {String} desc Description of the Scene. */
// Schema is the GraphQL schema served by the server. var Schema, _ = graphql.NewSchema(graphql.SchemaConfig{ Query: rootQuery, Mutation: rootMutation, Types: types, }) Query and Mutation
type Scene struct { ID int64 `xorm:"pk autoincr" json:"id"` Image string `json:"image,omitempty"` CreatedAt time.Time `json:"createdAt,omitempty"` UpdatedAt time.Time `json:"updatedAt,omitempty"` DeletedAt time.Time `xorm:"deleted"` // reference Items []*SceneItem `xorm:"-" json:"items,omitempty"` User *User `xorm:"-" json:"user,omitempty"` Role *SceneAccess `xorm:"-" json:"role,omitempty"` } Data Model user role permission
GET DATA FROM DATABASE IF NOT EXIST func userBatch(ctx context.Context, keys dataloader.Keys) []*dataloader.Result { var results []*dataloader.Result id, _ := helper.GetCacheID(keys[0].String()) user, err := model.GetUserByID(id.(int64)) results = append(results, &dataloader.Result{ Data: user, Error: err, }) return results } fetch from DB
func batchFunc(_ context.Context, keys dataloader.Keys) []*dataloader.Result { results := make([]*dataloader.Result, len(keys)) // get what you can from redis values, _ := redisClient.MGet(...keys.Keys()).Result() // make a list of everything that was not found in redis var cacheMisses map[int]string for i := range keys { if values[i] == redis.Nil { cacheMisses[i] = keys[i].String() } else { results[i] = &dataloader.Result{values[i], nil} } } // get the missing items from more expensive location (like DB) for idx, key := range cacheMisses { value, err := db.GetValues(key) // Pseudo code! redisClient.Set(key, value) results[idx] = &dataloader.Result{value, err} } return results } miss from redis fetch from DB