livebud / bud

The Full-Stack Web Framework for Go
MIT License
5.58k stars 179 forks source link

package/{di,parser}: add typespec support #379

Closed matthewmueller closed 1 year ago

matthewmueller commented 1 year ago

This PR adds support for dependency injection with custom types. For example, if you wanted to provide *View in the following example:

func LoadPages() (Pages, error) {
  return Pages{"index.svelte", "frame.svelte"}, nil
}

type Pages []string

func Load(pages Pages) *View {
  return &View{pages}
}

type View struct {
  pages Pages
}

The generated code would look something like:

// Generated. Do not edit
func load() (*View, error) {
  pages, err := LoadPages()
  if err != nil {
    return nil, err
  }
  view := Load(pages)
  return view, nil
}

Custom types do not try to initialize themselves (e.g. Pages{}). They need to be initialized with a function, so if LoadPages wasn't present, di would return an error.

I originally tried passing the empty value through, but it was just too easy for di to succeed, but you didn't actually get the dependency tree you expected.