Skip to content
This repository has been archived by the owner on Dec 8, 2022. It is now read-only.

Is there a way to make generated data optional? #161

Open
lexuzieel opened this issue Jul 12, 2022 · 1 comment
Open

Is there a way to make generated data optional? #161

lexuzieel opened this issue Jul 12, 2022 · 1 comment

Comments

@lexuzieel
Copy link

Sometimes it is useful to generate randomly optional fields, such as the last name (but really - almost any field).

Is it possible to do something like this:

firstName := faker.FirstName()
lastName := faker.Optional(.5).LastName() // <-- Generate non-empty last name 50% of the time

fullName := firstName
if lastName != "" {
    fullName += " " + lastName
}

println("Hello, " + fullName + "!")

Here faker.LastName() would return empty string 50% of the time.

@bxcodec
Copy link
Owner

bxcodec commented Aug 11, 2022

Is it possible to use a custom generator faker for that?

ref

faker/faker.go

Lines 405 to 456 in 72e5223

// AddProvider extend faker with tag to generate fake data with specified custom algorithm
// Example:
// type Gondoruwo struct {
// Name string
// Locatadata int
// }
//
// type Sample struct {
// ID int64 `faker:"customIdFaker"`
// Gondoruwo Gondoruwo `faker:"gondoruwo"`
// Danger string `faker:"danger"`
// }
//
// func CustomGenerator() {
// // explicit
// faker.AddProvider("customIdFaker", func(v reflect.Value) (interface{}, error) {
// return int64(43), nil
// })
// // functional
// faker.AddProvider("danger", func() faker.TaggedFunction {
// return func(v reflect.Value) (interface{}, error) {
// return "danger-ranger", nil
// }
// }())
// faker.AddProvider("gondoruwo", func(v reflect.Value) (interface{}, error) {
// obj := Gondoruwo{
// Name: "Power",
// Locatadata: 324,
// }
// return obj, nil
// })
// }
//
// func main() {
// CustomGenerator()
// var sample Sample
// faker.FakeData(&sample)
// fmt.Printf("%+v", sample)
// }
//
// Will print
// {ID:43 Gondoruwo:{Name:Power Locatadata:324} Danger:danger-ranger}
// Notes: when using a custom provider make sure to return the same type as the field
func AddProvider(tag string, provider TaggedFunction) error {
if _, ok := mapperTag[tag]; ok {
return errors.New(ErrTagAlreadyExists)
}
PriorityTags = append(PriorityTags, tag)
mapperTag[tag] = provider
return nil
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants