Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@a8m
Copy link
Member

@a8m a8m commented Oct 26, 2021

This PR automates the solution that is suggested in https://entgo.io/docs/faq#how-to-extend-the-generated-builders.

After this PR is landed, users that want to inject external dependencies to the generated API, can configure it as follows:

opts := []entc.Option{
	entc.Dependency(
		entc.DependencyType(&http.Client{}),
	),
	entc.Dependency(
		entc.DependencyName("Writer"),
		entc.DependencyTypeInfo(&field.TypeInfo{
			Ident:   "io.Writer",
			PkgPath: "io",
		}),
	),
}
if err := entc.Generate("./schema", &gen.Config{}, opts...); err != nil {
	log.Fatalf("running ent codegen: %v", err)
}

And then, use it in their application:

func Example_EntcPkg() {
	client, err := ent.Open(
		"sqlite3",
		"file:ent?mode=memory&cache=shared&_fk=1",
		ent.Writer(os.Stdout),
		ent.HTTPClient(http.DefaultClient),
	)
	if err != nil {
		log.Fatalf("failed opening connection to sqlite: %v", err)
	}
	defer client.Close()
	// A usage example of using the injected dependencies in the generated builders.
	client.User.Use(func(next ent.Mutator) ent.Mutator {
		return hook.UserFunc(func(ctx context.Context, m *ent.UserMutation) (ent.Value, error) {
			_ = m.HTTPClient
			_ = m.Writer
			return next.Mutate(ctx, m)
		})
	})
	// ...
}

@a8m a8m marked this pull request as ready for review October 26, 2021 12:39
@a8m
Copy link
Member Author

a8m commented Oct 26, 2021

Copy link
Contributor

@yonidavidson yonidavidson left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, the PR doesn't include docs update. are you planning on making one?

@masseelch
Copy link
Collaborator

Dope!

@a8m
Copy link
Member Author

a8m commented Oct 26, 2021

Merging it, and going to create another PR for updating the docs. Thanks for the review 🙏

@a8m a8m merged commit 82eeeb5 into master Oct 26, 2021
@a8m a8m deleted the optional-dep branch October 26, 2021 17:33
a8m added a commit that referenced this pull request Oct 26, 2021
a8m added a commit that referenced this pull request Oct 26, 2021
a8m added a commit that referenced this pull request Oct 27, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants