mirror of
https://github.com/kevin-DL/services.git
synced 2026-01-21 23:15:06 +00:00
don't inject an id if one exists in the db record (#288)
This commit is contained in:
@@ -21,6 +21,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const idKey = "id"
|
const idKey = "id"
|
||||||
|
const _idKey = "_id"
|
||||||
const stmt = "create table if not exists %v(id text not null, data jsonb, primary key(id)); alter table %v add created_at timestamptz; alter table %v add updated_at timestamptz"
|
const stmt = "create table if not exists %v(id text not null, data jsonb, primary key(id)); alter table %v add created_at timestamptz; alter table %v add updated_at timestamptz"
|
||||||
const truncateStmt = `truncate table "%v"`
|
const truncateStmt = `truncate table "%v"`
|
||||||
const dropTableStmt = `drop table "%v"`
|
const dropTableStmt = `drop table "%v"`
|
||||||
@@ -116,12 +117,13 @@ func (e *Db) Create(ctx context.Context, req *db.CreateRequest, rsp *db.CreateRe
|
|||||||
|
|
||||||
// check the record for an id field
|
// check the record for an id field
|
||||||
if len(id) == 0 {
|
if len(id) == 0 {
|
||||||
|
// try use an id from the record
|
||||||
if mid, ok := m[idKey].(string); ok {
|
if mid, ok := m[idKey].(string); ok {
|
||||||
id = mid
|
id = mid
|
||||||
} else {
|
} else {
|
||||||
// set id as uuid
|
// set id as uuid
|
||||||
id = uuid.New().String()
|
id = uuid.New().String()
|
||||||
// inject id into record
|
// inject into record
|
||||||
m[idKey] = id
|
m[idKey] = id
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -290,15 +292,28 @@ func (e *Db) Read(ctx context.Context, req *db.ReadRequest, rsp *db.ReadResponse
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
ma := map[string]interface{}{}
|
ma := map[string]interface{}{}
|
||||||
json.Unmarshal(m, &ma)
|
json.Unmarshal(m, &ma)
|
||||||
ma[idKey] = rec.ID
|
|
||||||
|
// only inject the ID if it does not exist
|
||||||
|
if id, ok := ma[idKey]; !ok {
|
||||||
|
ma[idKey] = rec.ID
|
||||||
|
} else if id != rec.ID {
|
||||||
|
// inject an _id key because
|
||||||
|
// they don't match e.g user defined
|
||||||
|
// an id field in their data
|
||||||
|
// and separately set an id
|
||||||
|
ma[_idKey] = rec.ID
|
||||||
|
}
|
||||||
|
|
||||||
m, _ = json.Marshal(ma)
|
m, _ = json.Marshal(ma)
|
||||||
s := &structpb.Struct{}
|
s := &structpb.Struct{}
|
||||||
err = s.UnmarshalJSON(m)
|
|
||||||
if err != nil {
|
if err = s.UnmarshalJSON(m); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
rsp.Records = append(rsp.Records, s)
|
rsp.Records = append(rsp.Records, s)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user