diff --git a/api.go b/api.go index 924c13a..cd78112 100644 --- a/api.go +++ b/api.go @@ -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 != "" { diff --git a/jsonapi/marshal.go b/jsonapi/marshal.go index 2db7250..699f72b 100644 --- a/jsonapi/marshal.go +++ b/jsonapi/marshal.go @@ -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 { @@ -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) +} diff --git a/jsonapi/route_namer.go b/jsonapi/route_namer.go new file mode 100644 index 0000000..46c77a0 --- /dev/null +++ b/jsonapi/route_namer.go @@ -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 +}