-
Notifications
You must be signed in to change notification settings - Fork 0
/
presenter.go
100 lines (81 loc) · 2.18 KB
/
presenter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package rest
import (
"bytes"
"encoding/json"
"net/http"
"time"
"github.com/tullo/invoice-mvp/domain"
)
// Interfaces
// InvoicePresenter ...
type InvoicePresenter interface {
Present(i interface{})
}
// Implementations
// CacheableActivities decorates activities with last modified date.
type CacheableActivities struct {
Activities []byte
LastModified time.Time
}
// ActivitiesPresenter implements the presenter interface.
type ActivitiesPresenter struct {
}
// NewActivitiesPresenter instantiates an activities presenter.
func NewActivitiesPresenter() ActivitiesPresenter {
return ActivitiesPresenter{}
}
// DefaultPresenter ...
type DefaultPresenter struct {
}
// NewDefaultPresenter ...
func NewDefaultPresenter() DefaultPresenter {
return DefaultPresenter{}
}
// JSONInvoicePresenter ...
type JSONInvoicePresenter struct {
writer http.ResponseWriter
}
// NewJSONInvoicePresenter ...
func NewJSONInvoicePresenter(w http.ResponseWriter) JSONInvoicePresenter {
return JSONInvoicePresenter{writer: w}
}
// PDFInvoicePresenter ...
type PDFInvoicePresenter struct {
writer http.ResponseWriter
request *http.Request
}
// NewPDFInvoicePresenter ...
func NewPDFInvoicePresenter(w http.ResponseWriter, r *http.Request) PDFInvoicePresenter {
return PDFInvoicePresenter{writer: w, request: r}
}
// Presentations
// Present knows how to present the activities list combined with the last
// modified date.
func (ActivitiesPresenter) Present(i interface{}) CacheableActivities {
lm := time.Unix(0, 0)
as := i.([]domain.Activity)
for _, a := range as {
if a.Updated.After(lm) {
lm = a.Updated
}
}
b, _ := json.Marshal(i)
return CacheableActivities{Activities: b, LastModified: lm}
}
// Present ...
func (p DefaultPresenter) Present(i interface{}) {
}
// Present ...
func (p JSONInvoicePresenter) Present(i interface{}) {
if b, err := json.Marshal(i); err == nil {
p.writer.Header().Set("Content-Type", "application/json")
p.writer.Write(b)
}
}
// Present ...
func (p PDFInvoicePresenter) Present(i interface{}) {
modTime := time.Now()
invoice := i.(domain.Invoice)
content := bytes.NewReader(invoice.ToPDF())
http.ServeContent(p.writer, p.request, "invoice.pdf", modTime, content)
}