|
| 1 | +package handler |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "net/http" |
| 6 | + "strings" |
| 7 | + |
| 8 | + problem "github.com/developer-overheid-nl/don-api-register/pkg/api_client/helpers/problem" |
| 9 | + "github.com/developer-overheid-nl/don-api-register/pkg/api_client/models" |
| 10 | + "github.com/gin-gonic/gin" |
| 11 | +) |
| 12 | + |
| 13 | +const ApisJsonLdMediaType = "application/ld+json" |
| 14 | + |
| 15 | +var apiDetailJsonLdContext = json.RawMessage(`{"dcat":"http://www.w3.org/ns/dcat#","dct":"http://purl.org/dc/terms/","vcard":"http://www.w3.org/2006/vcard/ns#","dcat:endpointDescription":{"@type":"@id"},"vcard:hasEmail":{"@type":"@id"},"vcard:hasURL":{"@type":"@id"},"dct:publisher":{"@type":"@id"}}`) |
| 16 | + |
| 17 | +func oasConformsToURL(version string) string { |
| 18 | + v := strings.TrimSpace(version) |
| 19 | + if v == "" { |
| 20 | + return "https://spec.openapis.org/oas" |
| 21 | + } |
| 22 | + return "https://spec.openapis.org/oas/v" + v + ".html" |
| 23 | +} |
| 24 | + |
| 25 | +// AcceptsJsonLd reports whether the Accept header explicitly requests application/ld+json. |
| 26 | +func AcceptsJsonLd(accept string) bool { |
| 27 | + for _, part := range strings.Split(accept, ",") { |
| 28 | + media := strings.TrimSpace(strings.SplitN(part, ";", 2)[0]) |
| 29 | + if strings.EqualFold(media, ApisJsonLdMediaType) { |
| 30 | + return true |
| 31 | + } |
| 32 | + } |
| 33 | + return false |
| 34 | +} |
| 35 | + |
| 36 | +// RetrieveApiJsonLd handles GET /apis/:id with Accept: application/ld+json. |
| 37 | +func (c *APIsAPIController) RetrieveApiJsonLd(ctx *gin.Context, params *models.ApiParams) error { |
| 38 | + api, err := c.Service.RetrieveApi(ctx.Request.Context(), params.Id) |
| 39 | + if err != nil { |
| 40 | + return err |
| 41 | + } |
| 42 | + if api == nil { |
| 43 | + return problem.NewNotFound(params.Id, "Api not found") |
| 44 | + } |
| 45 | + |
| 46 | + contact := models.ContactJsonLd{FN: api.Contact.Name} |
| 47 | + if api.Contact.Email != "" { |
| 48 | + contact.HasEmail = "mailto:" + api.Contact.Email |
| 49 | + } |
| 50 | + if api.Contact.URL != "" { |
| 51 | + contact.HasURL = api.Contact.URL |
| 52 | + } |
| 53 | + |
| 54 | + body := models.ApiDetailJsonLd{ |
| 55 | + Context: apiDetailJsonLdContext, |
| 56 | + Type: "dcat:DataService", |
| 57 | + ConformsTo: []string{oasConformsToURL(api.OasVersion)}, |
| 58 | + Identifier: api.Id, |
| 59 | + Title: api.Title, |
| 60 | + Description: api.Description, |
| 61 | + EndpointDescription: api.OasUrl, |
| 62 | + ContactPoint: contact, |
| 63 | + Publisher: api.Organisation.Uri, |
| 64 | + } |
| 65 | + data, err := json.Marshal(body) |
| 66 | + if err != nil { |
| 67 | + return err |
| 68 | + } |
| 69 | + ctx.Data(http.StatusOK, ApisJsonLdMediaType, data) |
| 70 | + return nil |
| 71 | +} |
0 commit comments