1
2
3
4
5
6
7 package mtest
8
9 import (
10 "go.mongodb.org/mongo-driver/bson"
11 )
12
13
14 type BatchIdentifier string
15
16
17 const (
18 FirstBatch BatchIdentifier = "firstBatch"
19 NextBatch BatchIdentifier = "nextBatch"
20 )
21
22
23 type CommandError struct {
24 Code int32
25 Message string
26 Name string
27 Labels []string
28 }
29
30
31 type WriteError struct {
32 Index int
33 Code int
34 Message string
35 }
36
37
38 type WriteConcernError struct {
39 Name string `bson:"codeName"`
40 Code int `bson:"code"`
41 Message string `bson:"errmsg"`
42 Details bson.Raw `bson:"errInfo"`
43 }
44
45
46 func CreateCursorResponse(cursorID int64, ns string, identifier BatchIdentifier, batch ...bson.D) bson.D {
47 batchArr := bson.A{}
48 for _, doc := range batch {
49 batchArr = append(batchArr, doc)
50 }
51
52 return bson.D{
53 {"ok", 1},
54 {"cursor", bson.D{
55 {"id", cursorID},
56 {"ns", ns},
57 {string(identifier), batchArr},
58 }},
59 }
60 }
61
62
63 func CreateCommandErrorResponse(ce CommandError) bson.D {
64 res := bson.D{
65 {"ok", 0},
66 {"code", ce.Code},
67 {"errmsg", ce.Message},
68 {"codeName", ce.Name},
69 }
70 if len(ce.Labels) > 0 {
71 var labelsArr bson.A
72 for _, label := range ce.Labels {
73 labelsArr = append(labelsArr, label)
74 }
75 res = append(res, bson.E{Key: "errorLabels", Value: labelsArr})
76 }
77 return res
78 }
79
80
81 func CreateWriteErrorsResponse(writeErrorrs ...WriteError) bson.D {
82 arr := make(bson.A, len(writeErrorrs))
83 for idx, we := range writeErrorrs {
84 arr[idx] = bson.D{
85 {"index", we.Index},
86 {"code", we.Code},
87 {"errmsg", we.Message},
88 }
89 }
90
91 return bson.D{
92 {"ok", 1},
93 {"writeErrors", arr},
94 }
95 }
96
97
98 func CreateWriteConcernErrorResponse(wce WriteConcernError) bson.D {
99 wceDoc := bson.D{
100 {"code", wce.Code},
101 {"codeName", wce.Name},
102 {"errmsg", wce.Message},
103 }
104 if len(wce.Details) > 0 {
105 wceDoc = append(wceDoc, bson.E{Key: "errInfo", Value: wce.Details})
106 }
107
108 return bson.D{
109 {"ok", 1},
110 {"writeConcernError", wceDoc},
111 }
112 }
113
114
115 func CreateSuccessResponse(elems ...bson.E) bson.D {
116 res := bson.D{
117 {"ok", 1},
118 }
119 return append(res, elems...)
120 }
121
View as plain text