goadesign / goadesign/goa

ConvertTo or CreateForm with constructor, factory or builder?

Open
#3,581 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
6.1k
Forks
583
Avg merge
2d 10h
Merged PRs (30d)
15

Description

Hi!

I’ve recently started developing with Goa, and I’m still learning about all its functionalities. I’m currently trying to convert a user-defined type into a struct in a library. For this specific example, I want to handle a currency code and amount, using the [currency](https://github.com/bojanz/currency) library for internal representation.

Here’s the code I’ve implemented so far. However, I noticed that the library internally uses private fields and only exposes constructors to create the `Amount` object:

```
var CurrencyType = Type("Currency", func() {
Description("Currency amount")
TypeName("CurrencyType")
ConvertTo(domain.Currency{})
Attribute("currencyCode", String, "Currency code in ISO 4217", func() {
Pattern(`^[A-Z]{3}$`)
Example("USD")
MaxLength(3)
MinLength(3)
})
Attribute("number", String, "Amount of currency", func() {
Pattern(`^\d+(\.\d{1,6})?$`)
Example("1234.56")
})
Required("currencyCode", "number")
})
```

The constructor provided by the library, which I find useful, is:

`
func NewAmount(n, currencyCode string) (Amount, error)
`

It’s straightforward to implement the conversion for the `CurrencyType` field in my own packages. However, when `CurrencyType` is part of a more complex user-defined type, I’m unsure how to specify the constructor instead of directly mapping fields during the conversion.

My question is: Is there a way to parameterize the constructor to map a specific field when using `ConvertTo`?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.