Request
Explore adding a variable declarations template to the BSON Transpiler templates.
ObjectIdSymbolDeclarationsTemplate: &ObjectIdSymbolDeclarationsTemplate null
|
Motivation
Go handles some functionality by returning both a value as well as any error encountered while parsing the value. For example, when trying to parse an objectID from hex, you would handle errors inline
objectID, err := primitive.ObjectIDFromHex("5ab901c29ee65f5c8550c5b9")
|
if err != nil {
|
log.Fatal(err)
|
}
|
|
// use objectID for something
|
While this follows the "go way" of error-handling, the `ObjectIdSymbolArgsTemplate`, for example, expects only functionality that will return an object id alone. This requires the go templates to use closures to handle errors that might occur at runtime
// This would be embedded in some CRUD Operation
|
// and is what would be transpiled from
|
// { _id: ObjectID("5ab901c29ee65f5c8550c5b9") }
|
bson.D{{"_id", func(hex string) primitive.ObjectID {
|
objectID, err := primitive.ObjectIDFromHex(hex)
|
if err != nil {
|
log.Fatal(err)
|
}
|
return objectID
|
}("5ab901c29ee65f5c8550c5b9")}}
|
This does not look very natural and could be a source of confusion for go developers trying to export code.
Proposal
The closure method may possibly be avoided by adding the new template `ObjectIdSymbolDeclarationsTemplate` where variables are declared to be used within the args template
ObjectIdSymbolDeclarationsTemplate: &ObjectIdSymbolDeclarationsTemplate !!js/function >
|
(arg, count) => {
|
return `objectID${count}, err := primitive.ObjectIDFromHex(${arg})
|
if err != nil {
|
log.Fatal(err)
|
}`
|
}
|
ObjectIdSymbolArgsTemplate: &ObjectIdSymbolArgsTemplate !!js/function >
|
(_, count) => {
|
return `objectID${count}`
|
}
|
This would be transpiled into the following
objectID1, err := primitive.ObjectIDFromHex("5ab901c29ee65f5c8550c5b9")
|
if err != nil {
|
log.Fatal(err)
|
}
|
|
// this would be embedded in some CRUD Operation
|
bson.D{{"_id", objectID1}}
|
|