我正在使用gqlgen,sqlx和pgx. 我正在嘗試為sqlx's使用自定義標(biāo)量types.JSONText。我jsonb在項目表中有這個屬性字段。-- migrations/001_up.sqlCREATE TABLE IF NOT EXISTS items ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), quantity INT NOT NULL, attributes JSONB);我有這些模型結(jié)構(gòu):// graph/model/item.gotype Item struct { ID string `json:"id,omitempty" db:"id,omitempty"` Quantity int `json:"quantity" db:"quantity"` Attributes *Attributes `json:"attributes,omitempty" db:"attributes,omitempty"`}type Attributes types.JSONText我有這個 graphql 架構(gòu):// graph/schema.graphqltype Item { id: ID! quantity: Int! attributes: Attributes} scalar Attributes我可以成功插入數(shù)據(jù)庫,但在檢索時出錯。| id | quantity | attributes ||---------------|----------|------------------------------------|| 031e1489-... | 100 | {"size": "medium", "color": "red"} |這是我從 db 查詢中得到的日志:>> items.Db: &{ 031e1489-02c9-46d3-924d-6a2edf1ca3ba // id 100 // quantity 0xc000430600 // attributes}我試圖編組屬性標(biāo)量:// graph/model/item.go...func (a *Attributes) MarshalGQL(w io.Writer) { b, _ := json.Marshal(a) w.Write(b)}// Unmarshal here...添加自定義標(biāo)量類型gqlgen.yml:... Attributes: model: - github.com/my-api/graph/model.Attributes但我得到的是字符串而不是 json:{ "data": { "item": { "id": "031e1489-02c9-46d3-924d-6a2edf1ca3ba", "quantity": 100, "attributes": "eyJjb2xvciI6ICJyZWQifQ==", } }}所需的輸出是:{ "data": { "item": { "id": "031e1489-02c9-46d3-924d-6a2edf1ca3ba", "quantity": 100, "attributes": { "size": "medium", "color": "red", } } }}我做錯了什么?
1 回答

暮色呼如
TA貢獻(xiàn)1853條經(jīng)驗 獲得超9個贊
Attributes使用types.JSONText定義 使用 定義 使用json.RawMessage定義[]byte。這意味著包括 在內(nèi)的所有 4 種類型的底層類型都是,這反過來意味著所有 4 種類型都可以轉(zhuǎn)換為。[]byte []byte[]byte
因此,這樣做就足夠了:
func (a *Attributes) MarshalGQL(w io.Writer) {
w.Write([]byte(*a))
}
- 1 回答
- 0 關(guān)注
- 132 瀏覽
添加回答
舉報
0/150
提交
取消