/
resolver.go
114 lines (96 loc) · 2.83 KB
/
resolver.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package resolvers
import (
"context"
"image/color"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/99designs/gqlgen/graphql"
"github.com/afocus/captcha"
"github.com/dollarkillerx/eim/internal/generated"
"github.com/dollarkillerx/eim/internal/storage"
"github.com/patrickmn/go-cache"
"github.com/pkg/errors"
"github.com/rs/xid"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Resolver ...
type Resolver struct {
Storage storage.Interface
cache *cache.Cache
captcha *captcha.Captcha
}
func NewResolver(db storage.Interface) *Resolver {
return &Resolver{
Storage: db,
cache: cache.New(15*time.Minute, 30*time.Minute),
captcha: captchaInit(),
}
}
func captchaInit() (cca *captcha.Captcha) {
cca = captcha.New()
// 可以设置多个字体 或使用cap.AddFont("xx.ttf")追加
cca.SetFont("./static/comic.ttf")
// 设置验证码大小
cca.SetSize(150, 64)
// 设置干扰强度
cca.SetDisturbance(captcha.MEDIUM)
// 设置前景色 可以多个 随机替换文字颜色 默认黑色
cca.SetFrontColor(color.RGBA{255, 255, 255, 255})
// 设置背景色 可以多个 随机替换背景色 默认白色
cca.SetBkgColor(color.RGBA{255, 0, 0, 255}, color.RGBA{0, 0, 255, 255}, color.RGBA{0, 153, 0, 255})
return
}
// Mutation is the root mutation resolver
func (r *Resolver) Mutation() generated.MutationResolver {
return &mutationResolver{r}
}
// Query is the root query resolver
func (r *Resolver) Query() generated.QueryResolver {
return &queryResolver{r}
}
type mutationResolver struct{ *Resolver }
func (r *mutationResolver) Healthcheck(ctx context.Context) (string, error) {
return "ack", nil
}
type queryResolver struct{ *Resolver }
func (r *queryResolver) Healthcheck(ctx context.Context) (string, error) {
return "ack", nil
}
func (r *queryResolver) Now(ctx context.Context) (*timestamppb.Timestamp, error) {
return ×tamppb.Timestamp{
Seconds: time.Now().Unix(),
}, nil
}
// field resolver
type fileInfoResolver struct{ *Resolver }
// UploadFile ...
func (r *mutationResolver) UploadFile(ctx context.Context, file graphql.Upload) (string, error) {
// 检查上传的文件是否符合要求
maxSize := int64(8 * 1024 * 1024) // 8MB
if file.Size > maxSize {
return "", errors.New("file size too large")
}
// 生成新的文件名
newFileName := xid.New().String() + filepath.Ext(file.Filename)
// 打开文件,准备写入
targetFile, err := os.OpenFile("./static/"+newFileName, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return "", err
}
defer targetFile.Close()
// 从上传的文件中读取数据,并写入到打开的文件中
fileData, err := ioutil.ReadAll(file.File)
if err != nil {
return "", err
}
_, err = io.Copy(targetFile, strings.NewReader(string(fileData)))
if err != nil {
return "", err
}
// 返回新的文件名
return newFileName, nil
}