-
Notifications
You must be signed in to change notification settings - Fork 10
/
worker.go
85 lines (73 loc) · 2.32 KB
/
worker.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
package publish
import (
"fmt"
"strings"
"github.com/qor/admin"
"github.com/qor/qor"
"github.com/qor/roles"
"github.com/qor/worker"
)
type workerJobLogger struct {
job worker.QorJobInterface
}
func (job workerJobLogger) Print(results ...interface{}) {
job.job.AddLog(fmt.Sprint(results...))
}
// QorWorkerArgument used for qor publish job's argument
type QorWorkerArgument struct {
IDs []string
worker.Schedule
}
// SetWorker set publish's worker
func (publish *Publish) SetWorker(w *worker.Worker) {
publish.WorkerScheduler = w
publish.registerWorkerJob()
}
func (publish *Publish) registerWorkerJob() {
if w := publish.WorkerScheduler; w != nil {
if w.Admin == nil {
fmt.Println("Need to add worker to admin first before set worker")
return
}
qorWorkerArgumentResource := w.Admin.NewResource(&QorWorkerArgument{})
qorWorkerArgumentResource.Meta(&admin.Meta{Name: "IDs", Type: "publish_job_argument", Valuer: func(record interface{}, context *qor.Context) interface{} {
var values = map[*admin.Resource][][]string{}
if workerArgument, ok := record.(*QorWorkerArgument); ok {
for _, id := range workerArgument.IDs {
if keys := strings.Split(id, "__"); len(keys) >= 2 {
name, id := keys[0], keys[1:]
recordRes := w.Admin.GetResource(name)
values[recordRes] = append(values[recordRes], id)
}
}
}
return values
}})
w.RegisterJob(&worker.Job{
Name: "Publish",
Group: "Publish",
Permission: roles.Deny(roles.Read, roles.Anyone),
Handler: func(argument interface{}, job worker.QorJobInterface) error {
if argu, ok := argument.(*QorWorkerArgument); ok {
records := publish.searchWithPublishIDs(publish.DraftDB(), w.Admin, argu.IDs)
publish.Logger(&workerJobLogger{job: job}).Publish(records...)
}
return nil
},
Resource: qorWorkerArgumentResource,
})
w.RegisterJob(&worker.Job{
Name: "Discard",
Group: "Publish",
Permission: roles.Deny(roles.Read, roles.Anyone),
Handler: func(argument interface{}, job worker.QorJobInterface) error {
if argu, ok := argument.(*QorWorkerArgument); ok {
records := publish.searchWithPublishIDs(publish.DraftDB(), w.Admin, argu.IDs)
publish.Logger(&workerJobLogger{job: job}).Discard(records...)
}
return nil
},
Resource: qorWorkerArgumentResource,
})
}
}