1package main
2
3import (
4	"fmt"
5	"time"
6
7	"github.com/google/jsonapi"
8)
9
10// Blog is a model representing a blog site
11type Blog struct {
12	ID            int       `jsonapi:"primary,blogs"`
13	Title         string    `jsonapi:"attr,title"`
14	Posts         []*Post   `jsonapi:"relation,posts"`
15	CurrentPost   *Post     `jsonapi:"relation,current_post"`
16	CurrentPostID int       `jsonapi:"attr,current_post_id"`
17	CreatedAt     time.Time `jsonapi:"attr,created_at"`
18	ViewCount     int       `jsonapi:"attr,view_count"`
19}
20
21// Post is a model representing a post on a blog
22type Post struct {
23	ID       int        `jsonapi:"primary,posts"`
24	BlogID   int        `jsonapi:"attr,blog_id"`
25	Title    string     `jsonapi:"attr,title"`
26	Body     string     `jsonapi:"attr,body"`
27	Comments []*Comment `jsonapi:"relation,comments"`
28}
29
30// Comment is a model representing a user submitted comment
31type Comment struct {
32	ID     int    `jsonapi:"primary,comments"`
33	PostID int    `jsonapi:"attr,post_id"`
34	Body   string `jsonapi:"attr,body"`
35}
36
37// JSONAPILinks implements the Linkable interface for a blog
38func (blog Blog) JSONAPILinks() *jsonapi.Links {
39	return &jsonapi.Links{
40		"self": fmt.Sprintf("https://example.com/blogs/%d", blog.ID),
41	}
42}
43
44// JSONAPIRelationshipLinks implements the RelationshipLinkable interface for a blog
45func (blog Blog) JSONAPIRelationshipLinks(relation string) *jsonapi.Links {
46	if relation == "posts" {
47		return &jsonapi.Links{
48			"related": fmt.Sprintf("https://example.com/blogs/%d/posts", blog.ID),
49		}
50	}
51	if relation == "current_post" {
52		return &jsonapi.Links{
53			"related": fmt.Sprintf("https://example.com/blogs/%d/current_post", blog.ID),
54		}
55	}
56	return nil
57}
58
59// JSONAPIMeta implements the Metable interface for a blog
60func (blog Blog) JSONAPIMeta() *jsonapi.Meta {
61	return &jsonapi.Meta{
62		"detail": "extra details regarding the blog",
63	}
64}
65
66// JSONAPIRelationshipMeta implements the RelationshipMetable interface for a blog
67func (blog Blog) JSONAPIRelationshipMeta(relation string) *jsonapi.Meta {
68	if relation == "posts" {
69		return &jsonapi.Meta{
70			"detail": "posts meta information",
71		}
72	}
73	if relation == "current_post" {
74		return &jsonapi.Meta{
75			"detail": "current post meta information",
76		}
77	}
78	return nil
79}
80