Skip to content

Commit

Permalink
add insert method
Browse files Browse the repository at this point in the history
  • Loading branch information
cjp2600 committed Apr 16, 2019
1 parent f13b272 commit 90a5193
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 6 deletions.
43 changes: 42 additions & 1 deletion plugin/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ func (p *MongoPlugin) Generate(file *generator.FileDescriptor) {
p.PluginImports = generator.NewPluginImports(p.Generator)
p.localName = generator.FileName(file)
p.usePrimitive = false

for _, msg := range file.GetMessageType() {
if bomMessage, ok := p.getMessageOptions(msg); ok {
if bomMessage.GetModel() {
Expand All @@ -65,6 +64,7 @@ func (p *MongoPlugin) Generate(file *generator.FileDescriptor) {
p.GenerateToPB(msg)
p.GenerateToObject(msg)
p.GenerateBomConnect(msg)
p.GenerateInsertMethod(msg)
}
}
}
Expand Down Expand Up @@ -102,6 +102,47 @@ func (p *MongoPlugin) getFieldOptions(field *descriptor.FieldDescriptorProto) *b
return opts
}

//GenerateInsertMethod
func (p *MongoPlugin) GenerateInsertMethod(message *descriptor.DescriptorProto) {
//typeName := p.GenerateName(message.GetName())
mName := p.GenerateName(message.GetName())
p.usePrimitive = true
useId := false

p.P(`func (e *`, mName, `) Insert(bom *bom.Bom) (*`, mName, `, error) {`)

for _, field := range message.GetField() {
fieldName := field.GetName()
fieldName = generator.CamelCase(fieldName)

bomField := p.getFieldOptions(field)
if bomField != nil && bomField.Tag.GetMongoObjectId() {
if bomField.GetTag().GetIsID() {
useId = true
p.P(`e.`, fieldName, ` = primitive.NewObjectID() // create object id`)
}
}
}

if useId {
p.P(`res, err := e.WithBom(bom).InsertOne(e)`)
} else {
p.P(`_, err := e.WithBom(bom).InsertOne(e)`)
}
p.P(`if err != nil {`)
p.P(`return nil, err`)
p.P(`}`)

if useId {
p.P(`if insertId, ok := res.InsertedID.(primitive.ObjectID); ok {`)
p.P(`e.Id = insertId`)
p.P(`}`)
}

p.P(`return e, nil`)
p.P(`}`)
}

//GenerateBehaviorInterface
func (p *MongoPlugin) GenerateBehaviorInterface(message *descriptor.DescriptorProto) {
p.In()
Expand Down
67 changes: 62 additions & 5 deletions test.pb.bom.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 90a5193

Please sign in to comment.