| 38 | } |
| 39 | |
| 40 | func Example_subscription() { |
| 41 | gql := `subscription test { |
| 42 | users(id: $id) { |
| 43 | id |
| 44 | email |
| 45 | phone |
| 46 | } |
| 47 | }` |
| 48 | |
| 49 | vars := json.RawMessage(`{ "id": 3 }`) |
| 50 | |
| 51 | conf := newConfig(&core.Config{DBType: dbType, DisableAllowList: true, SubsPollDuration: 1}) |
| 52 | gj, err := core.NewGraphJin(conf, db) |
| 53 | if err != nil { |
| 54 | panic(err) |
| 55 | } |
| 56 | defer gj.Close() |
| 57 | |
| 58 | m, err := gj.Subscribe(context.Background(), gql, vars, nil) |
| 59 | if err != nil { |
| 60 | fmt.Println(err) |
| 61 | return |
| 62 | } |
| 63 | for i := 0; i < 10; i++ { |
| 64 | msg := <-m.Result |
| 65 | printJSON(msg.Data) |
| 66 | |
| 67 | // update user phone in database to trigger subscription |
| 68 | if dbType == "mongodb" { |
| 69 | // MongoDB: use JSON DSL for update |
| 70 | q := fmt.Sprintf(`{"operation":"updateOne","collection":"users","filter":{"_id":3},"update":{"$set":{"phone":"650-447-000%d"}}}`, i) |
| 71 | if _, err := db.Exec(q); err != nil { |
| 72 | panic(err) |
| 73 | } |
| 74 | } else { |
| 75 | // SQL databases: use SQL update |
| 76 | q := fmt.Sprintf(`UPDATE users SET phone = '650-447-000%d' WHERE id = 3`, i) |
| 77 | if _, err := db.Exec(q); err != nil { |
| 78 | panic(err) |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | // Output: |
| 83 | // {"users":{"email":"user3@test.com","id":3,"phone":null}} |
| 84 | // {"users":{"email":"user3@test.com","id":3,"phone":"650-447-0000"}} |
| 85 | // {"users":{"email":"user3@test.com","id":3,"phone":"650-447-0001"}} |
| 86 | // {"users":{"email":"user3@test.com","id":3,"phone":"650-447-0002"}} |
| 87 | // {"users":{"email":"user3@test.com","id":3,"phone":"650-447-0003"}} |
| 88 | // {"users":{"email":"user3@test.com","id":3,"phone":"650-447-0004"}} |
| 89 | // {"users":{"email":"user3@test.com","id":3,"phone":"650-447-0005"}} |
| 90 | // {"users":{"email":"user3@test.com","id":3,"phone":"650-447-0006"}} |
| 91 | // {"users":{"email":"user3@test.com","id":3,"phone":"650-447-0007"}} |
| 92 | // {"users":{"email":"user3@test.com","id":3,"phone":"650-447-0008"}} |
| 93 | } |
| 94 | |
| 95 | func Example_subscriptionWithCursor() { |
| 96 | // func TestSubCursor(t *testing.T) { |