-
Quick question, I have an endpoint protected by an authHandler in which I extract the user data with //encore:api auth
func ListCollections(ctx context.Context) (*ListCollectionsResponse, error) {
userData := auth.Data().(*identity.UserData)
collections, err := models.ListCollections(ctx, userData.ID)
if err != nil {
log.WithError(err).Warning("Could not fetch collections for this user")
return nil, &errs.Error{
Code: errs.Internal,
Message: "Could not fetch collections",
}
}
return &ListCollectionsResponse{
Collections: convert.CollectionModelsToPayloads(collections),
}, nil
} I took a look at the runtime code from encode (Which is exposed by the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I've thought about this as well and we should definitely do something to make this easier to test (probably add the ability to inject auth data into an API call by wrapping the context, or something like that). Until then, I suggest taking the business logic part and extracting it as a separate function that takes the auth data as a parameter: //encore:api auth
func ListCollections(ctx context.Context) (*ListCollectionsResponse, error) {
userData := auth.Data().(*identity.UserData)
return listCollections(ctx, userData)
}
func listCollections(ctx context.Context, userData *identity.UserData) (*ListCollectionsResponse, error) {
collections, err := models.ListCollections(ctx, userData.ID)
if err != nil {
log.WithError(err).Warning("Could not fetch collections for this user")
return nil, &errs.Error{
Code: errs.Internal,
Message: "Could not fetch collections",
}
}
return &ListCollectionsResponse{
Collections: convert.CollectionModelsToPayloads(collections),
}, nil
} And then write tests against |
Beta Was this translation helpful? Give feedback.
I've thought about this as well and we should definitely do something to make this easier to test (probably add the ability to inject auth data into an API call by wrapping the context, or something like that).
Until then, I suggest taking the business logic part and extracting it as a separate function that takes the auth data as a parameter: