generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 5
/
ad.go
62 lines (51 loc) 路 1.03 KB
/
ad.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
//ftl:module ad
package ad
import (
"context"
_ "embed"
"math/rand"
"golang.org/x/exp/maps"
"github.com/TBD54566975/ftl/examples/online-boutique/common"
)
const maxAdsToServe = 2
var (
//go:embed database.json
databaseJSON []byte
database = common.LoadDatabase[map[string]Ad](databaseJSON)
)
type AdRequest struct {
ContextKeys []string
}
type Ad struct {
RedirectURL string
Text string
}
type AdResponse struct {
Ads []Ad
}
//ftl:verb
func GetAds(ctx context.Context, req AdRequest) (AdResponse, error) {
resp := AdResponse{}
if len(req.ContextKeys) > 0 {
resp.Ads = contextualAds(req.ContextKeys)
}
if len(resp.Ads) == 0 {
resp.Ads = randomAds()
}
return resp, nil
}
func contextualAds(contextKeys []string) (ads []Ad) {
for _, key := range contextKeys {
if ad, ok := database[key]; ok {
ads = append(ads, ad)
}
}
return ads
}
func randomAds() (ads []Ad) {
allAds := maps.Values(database)
for i := 0; i < maxAdsToServe; i++ {
ads = append(ads, allAds[rand.Intn(len(allAds))])
}
return ads
}