Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding RouteNamer interface #324

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,12 @@ func (api *API) addResource(prototype jsonapi.MarshalIdentifier, source interfac
return info
}

// check if EntityNamer interface is implemented and use that as name
routeName, ok := prototype.(jsonapi.RouteNamer)
if ok {
name = routeName.GetRouteName()
}

prefix := strings.Trim(api.info.prefix, "/")
baseURL := "/" + name
if prefix != "" {
Expand Down
12 changes: 10 additions & 2 deletions jsonapi/marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -393,13 +393,13 @@ func getStructRelationships(relationer MarshalLinkedRelations, information Serve
func getLinkBaseURL(element MarshalIdentifier, information ServerInformation) string {
prefix := strings.Trim(information.GetBaseURL(), "/")
namespace := strings.Trim(information.GetPrefix(), "/")
structType := getStructType(element)
routeName := getRouteName(element)

if namespace != "" {
prefix += "/" + namespace
}

return fmt.Sprintf("%s/%s/%s", prefix, structType, element.GetID())
return fmt.Sprintf("%s/%s/%s", prefix, routeName, element.GetID())
}

func getLinksForServerInformation(relationer MarshalLinkedRelations, name string, information ServerInformation) Links {
Expand Down Expand Up @@ -458,3 +458,11 @@ func getStructType(data interface{}) string {

return Pluralize(Jsonify(reflectType.Name()))
}

func getRouteName(data interface{}) string {
routeName, ok := data.(RouteNamer)
if ok {
return routeName.GetRouteName()
}
return getStructType(data)
}
9 changes: 9 additions & 0 deletions jsonapi/route_namer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package jsonapi

// The RouteNamer interface can be optionally implemented to directly return the
// name of route used for the "type" field.
//
// Note: By default the name is guessed from the struct name or from EntityNamer.
type RouteNamer interface {
GetRouteName() string
}