API: rig up labels

This commit is contained in:
Drew DeVault 2021-02-15 10:08:01 -05:00
parent 114a5665c1
commit 51961a6b25
7 changed files with 540 additions and 53 deletions

View File

@ -42,6 +42,7 @@ type ResolverRoot interface {
Comment() CommentResolver
Created() CreatedResolver
Event() EventResolver
Label() LabelResolver
LabelUpdate() LabelUpdateResolver
Query() QueryResolver
StatusChange() StatusChangeResolver
@ -126,9 +127,9 @@ type ComplexityRoot struct {
Label struct {
BackgroundColor func(childComplexity int) int
Created func(childComplexity int) int
ForegroundColor func(childComplexity int) int
ID func(childComplexity int) int
Name func(childComplexity int) int
TextColor func(childComplexity int) int
Tickets func(childComplexity int, cursor *model1.Cursor) int
Tracker func(childComplexity int) int
}
@ -292,6 +293,11 @@ type CreatedResolver interface {
type EventResolver interface {
Ticket(ctx context.Context, obj *model.Event) (*model.Ticket, error)
}
type LabelResolver interface {
Tracker(ctx context.Context, obj *model.Label) (*model.Tracker, error)
Tickets(ctx context.Context, obj *model.Label, cursor *model1.Cursor) (*model.TicketCursor, error)
}
type LabelUpdateResolver interface {
Ticket(ctx context.Context, obj *model.LabelUpdate) (*model.Ticket, error)
Labeler(ctx context.Context, obj *model.LabelUpdate) (model.Entity, error)
@ -615,6 +621,13 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in
return e.complexity.Label.Created(childComplexity), true
case "Label.foregroundColor":
if e.complexity.Label.ForegroundColor == nil {
break
}
return e.complexity.Label.ForegroundColor(childComplexity), true
case "Label.id":
if e.complexity.Label.ID == nil {
break
@ -629,13 +642,6 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in
return e.complexity.Label.Name(childComplexity), true
case "Label.textColor":
if e.complexity.Label.TextColor == nil {
break
}
return e.complexity.Label.TextColor(childComplexity), true
case "Label.tickets":
if e.complexity.Label.Tickets == nil {
break
@ -1423,9 +1429,7 @@ enum AccessKind {
}
# Decorates fields for which access requires a particular OAuth 2.0 scope with
# read or write access. For the meta.sr.ht API, you have access to all public
# information without any special permissions - user profile information,
# public keys, and so on.
# read or write access.
directive @access(scope: AccessScope!, kind: AccessKind!) on FIELD_DEFINITION
# https://semver.org
@ -1601,7 +1605,7 @@ type Label {
# In CSS hexadecimal format
backgroundColor: String!
textColor: String!
foregroundColor: String!
tickets(cursor: Cursor): TicketCursor! @access(scope: TICKETS, kind: RO)
}
@ -3467,15 +3471,15 @@ func (ec *executionContext) _Label_tracker(ctx context.Context, field graphql.Co
Object: "Label",
Field: field,
Args: nil,
IsMethod: false,
IsResolver: false,
IsMethod: true,
IsResolver: true,
}
ctx = graphql.WithFieldContext(ctx, fc)
resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {
directive0 := func(rctx context.Context) (interface{}, error) {
ctx = rctx // use context from middleware stack in children
return obj.Tracker, nil
return ec.resolvers.Label().Tracker(rctx, obj)
}
directive1 := func(ctx context.Context) (interface{}, error) {
scope, err := ec.unmarshalNAccessScope2gitᚗsrᚗhtᚋאsircmpwnᚋtodoᚗsrᚗhtᚋapiᚋgraphᚋmodelᚐAccessScope(ctx, "TRACKERS")
@ -3554,7 +3558,7 @@ func (ec *executionContext) _Label_backgroundColor(ctx context.Context, field gr
return ec.marshalNString2string(ctx, field.Selections, res)
}
func (ec *executionContext) _Label_textColor(ctx context.Context, field graphql.CollectedField, obj *model.Label) (ret graphql.Marshaler) {
func (ec *executionContext) _Label_foregroundColor(ctx context.Context, field graphql.CollectedField, obj *model.Label) (ret graphql.Marshaler) {
defer func() {
if r := recover(); r != nil {
ec.Error(ctx, ec.Recover(ctx, r))
@ -3572,7 +3576,7 @@ func (ec *executionContext) _Label_textColor(ctx context.Context, field graphql.
ctx = graphql.WithFieldContext(ctx, fc)
resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {
ctx = rctx // use context from middleware stack in children
return obj.TextColor, nil
return obj.ForegroundColor, nil
})
if err != nil {
ec.Error(ctx, err)
@ -3600,8 +3604,8 @@ func (ec *executionContext) _Label_tickets(ctx context.Context, field graphql.Co
Object: "Label",
Field: field,
Args: nil,
IsMethod: false,
IsResolver: false,
IsMethod: true,
IsResolver: true,
}
ctx = graphql.WithFieldContext(ctx, fc)
@ -3615,7 +3619,7 @@ func (ec *executionContext) _Label_tickets(ctx context.Context, field graphql.Co
resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {
directive0 := func(rctx context.Context) (interface{}, error) {
ctx = rctx // use context from middleware stack in children
return obj.Tickets, nil
return ec.resolvers.Label().Tickets(rctx, obj, args["cursor"].(*model1.Cursor))
}
directive1 := func(ctx context.Context) (interface{}, error) {
scope, err := ec.unmarshalNAccessScope2gitᚗsrᚗhtᚋאsircmpwnᚋtodoᚗsrᚗhtᚋapiᚋgraphᚋmodelᚐAccessScope(ctx, "TICKETS")
@ -9255,38 +9259,56 @@ func (ec *executionContext) _Label(ctx context.Context, sel ast.SelectionSet, ob
case "id":
out.Values[i] = ec._Label_id(ctx, field, obj)
if out.Values[i] == graphql.Null {
invalids++
atomic.AddUint32(&invalids, 1)
}
case "created":
out.Values[i] = ec._Label_created(ctx, field, obj)
if out.Values[i] == graphql.Null {
invalids++
atomic.AddUint32(&invalids, 1)
}
case "name":
out.Values[i] = ec._Label_name(ctx, field, obj)
if out.Values[i] == graphql.Null {
invalids++
atomic.AddUint32(&invalids, 1)
}
case "tracker":
out.Values[i] = ec._Label_tracker(ctx, field, obj)
if out.Values[i] == graphql.Null {
invalids++
}
field := field
out.Concurrently(i, func() (res graphql.Marshaler) {
defer func() {
if r := recover(); r != nil {
ec.Error(ctx, ec.Recover(ctx, r))
}
}()
res = ec._Label_tracker(ctx, field, obj)
if res == graphql.Null {
atomic.AddUint32(&invalids, 1)
}
return res
})
case "backgroundColor":
out.Values[i] = ec._Label_backgroundColor(ctx, field, obj)
if out.Values[i] == graphql.Null {
invalids++
atomic.AddUint32(&invalids, 1)
}
case "textColor":
out.Values[i] = ec._Label_textColor(ctx, field, obj)
case "foregroundColor":
out.Values[i] = ec._Label_foregroundColor(ctx, field, obj)
if out.Values[i] == graphql.Null {
invalids++
atomic.AddUint32(&invalids, 1)
}
case "tickets":
out.Values[i] = ec._Label_tickets(ctx, field, obj)
if out.Values[i] == graphql.Null {
invalids++
}
field := field
out.Concurrently(i, func() (res graphql.Marshaler) {
defer func() {
if r := recover(); r != nil {
ec.Error(ctx, ec.Recover(ctx, r))
}
}()
res = ec._Label_tickets(ctx, field, obj)
if res == graphql.Null {
atomic.AddUint32(&invalids, 1)
}
return res
})
default:
panic("unknown field " + strconv.Quote(field.Name))
}

102
api/graph/model/label.go Normal file
View File

@ -0,0 +1,102 @@
package model
import (
"context"
"database/sql"
"strconv"
"time"
sq "github.com/Masterminds/squirrel"
"git.sr.ht/~sircmpwn/core-go/database"
"git.sr.ht/~sircmpwn/core-go/model"
)
type Label struct {
ID int `json:"id"`
Created time.Time `json:"created"`
Name string `json:"name"`
BackgroundColor string `json:"backgroundColor"`
ForegroundColor string `json:"foregroundColor"`
TrackerID int
alias string
fields *database.ModelFields
}
func (l *Label) As(alias string) *Label {
l.alias = alias
return l
}
func (l *Label) Alias() string {
return l.alias
}
func (l *Label) Table() string {
return `"label"`
}
func (l *Label) Fields() *database.ModelFields {
if l.fields != nil {
return l.fields
}
l.fields = &database.ModelFields{
Fields: []*database.FieldMap{
{ "id", "id", &l.ID },
{ "created", "created", &l.Created },
{ "name", "name", &l.Name },
{ "color", "backgroundColor", &l.BackgroundColor },
{ "text_color", "foregroundColor", &l.ForegroundColor },
// Always fetch:
{ "id", "", &l.ID },
{ "tracker_id", "", &l.TrackerID },
},
}
return l.fields
}
func (l *Label) QueryWithCursor(ctx context.Context, runner sq.BaseRunner,
q sq.SelectBuilder, cur *model.Cursor) ([]*Label, *model.Cursor) {
var (
err error
rows *sql.Rows
)
if cur.Next != "" {
next, _ := strconv.ParseInt(cur.Next, 10, 64)
q = q.Where(database.WithAlias(l.alias, "id")+"<= ?", next)
}
q = q.
OrderBy(database.WithAlias(l.alias, "id")).
Limit(uint64(cur.Count + 1))
if rows, err = q.RunWith(runner).QueryContext(ctx); err != nil {
panic(err)
}
defer rows.Close()
var labels []*Label
for rows.Next() {
var label Label
if err := rows.Scan(database.Scan(ctx, &label)...); err != nil {
panic(err)
}
labels = append(labels, &label)
}
if len(labels) > cur.Count {
cur = &model.Cursor{
Count: cur.Count,
Next: strconv.Itoa(labels[len(labels)-1].ID),
Search: cur.Search,
}
labels = labels[:cur.Count]
} else {
cur = nil
}
return labels, cur
}

View File

@ -53,16 +53,6 @@ type EventCursor struct {
Cursor *model.Cursor `json:"cursor"`
}
type Label struct {
ID int `json:"id"`
Created time.Time `json:"created"`
Name string `json:"name"`
Tracker *Tracker `json:"tracker"`
BackgroundColor string `json:"backgroundColor"`
TextColor string `json:"textColor"`
Tickets *TicketCursor `json:"tickets"`
}
type LabelCursor struct {
Results []*Label `json:"results"`
Cursor *model.Cursor `json:"cursor"`

View File

@ -19,9 +19,7 @@ enum AccessKind {
}
# Decorates fields for which access requires a particular OAuth 2.0 scope with
# read or write access. For the meta.sr.ht API, you have access to all public
# information without any special permissions - user profile information,
# public keys, and so on.
# read or write access.
directive @access(scope: AccessScope!, kind: AccessKind!) on FIELD_DEFINITION
# https://semver.org
@ -197,7 +195,7 @@ type Label {
# In CSS hexadecimal format
backgroundColor: String!
textColor: String!
foregroundColor: String!
tickets(cursor: Cursor): TicketCursor! @access(scope: TICKETS, kind: RO)
}

View File

@ -66,6 +66,35 @@ func (r *eventResolver) Ticket(ctx context.Context, obj *model.Event) (*model.Ti
return loaders.ForContext(ctx).TicketsByID.Load(obj.TicketID)
}
func (r *labelResolver) Tracker(ctx context.Context, obj *model.Label) (*model.Tracker, error) {
return loaders.ForContext(ctx).TrackersByID.Load(obj.TrackerID)
}
func (r *labelResolver) Tickets(ctx context.Context, obj *model.Label, cursor *coremodel.Cursor) (*model.TicketCursor, error) {
if cursor == nil {
cursor = coremodel.NewCursor(nil)
}
var tickets []*model.Ticket
if err := database.WithTx(ctx, &sql.TxOptions{
Isolation: 0,
ReadOnly: true,
}, func(tx *sql.Tx) error {
ticket := (&model.Ticket{}).As(`tk`)
query := database.
Select(ctx, ticket).
From(`ticket tk`).
Join(`ticket_label tl ON tl.ticket_id = tk.id`).
Where(`tl.label_id = ?`, obj.ID)
tickets, cursor = ticket.QueryWithCursor(ctx, tx, query, cursor)
return nil
}); err != nil {
return nil, err
}
return &model.TicketCursor{tickets, cursor}, nil
}
func (r *labelUpdateResolver) Ticket(ctx context.Context, obj *model.LabelUpdate) (*model.Ticket, error) {
return loaders.ForContext(ctx).TicketsByID.Load(obj.TicketID)
}
@ -75,7 +104,7 @@ func (r *labelUpdateResolver) Labeler(ctx context.Context, obj *model.LabelUpdat
}
func (r *labelUpdateResolver) Label(ctx context.Context, obj *model.LabelUpdate) (*model.Label, error) {
panic(fmt.Errorf("not implemented"))
return loaders.ForContext(ctx).LabelsByID.Load(obj.LabelID)
}
func (r *queryResolver) Version(ctx context.Context) (*model.Version, error) {
@ -189,7 +218,39 @@ func (r *ticketResolver) Tracker(ctx context.Context, obj *model.Ticket) (*model
}
func (r *ticketResolver) Labels(ctx context.Context, obj *model.Ticket) ([]*model.Label, error) {
panic(fmt.Errorf("not implemented"))
var labels []*model.Label
if err := database.WithTx(ctx, &sql.TxOptions{
Isolation: 0,
ReadOnly: true,
}, func(tx *sql.Tx) error {
var (
err error
rows *sql.Rows
)
label := (&model.Label{}).As(`l`)
query := database.
Select(ctx, label).
From(`label l`).
Join(`ticket_label tl ON tl.label_id = l.id`).
Where(`tl.ticket_id = ?`, obj.PKID)
if rows, err = query.RunWith(tx).QueryContext(ctx); err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var label model.Label
if err := rows.Scan(database.Scan(ctx, &label)...); err != nil {
panic(err)
}
labels = append(labels, &label)
}
return nil
}); err != nil {
return nil, err
}
return labels, nil
}
func (r *ticketResolver) Assignees(ctx context.Context, obj *model.Ticket) ([]model.Entity, error) {
@ -290,7 +351,27 @@ func (r *trackerResolver) Tickets(ctx context.Context, obj *model.Tracker, curso
}
func (r *trackerResolver) Labels(ctx context.Context, obj *model.Tracker, cursor *coremodel.Cursor) (*model.LabelCursor, error) {
panic(fmt.Errorf("not implemented"))
if cursor == nil {
cursor = coremodel.NewCursor(nil)
}
var labels []*model.Label
if err := database.WithTx(ctx, &sql.TxOptions{
Isolation: 0,
ReadOnly: true,
}, func(tx *sql.Tx) error {
label := (&model.Label{}).As(`l`)
query := database.
Select(ctx, label).
From(`label l`).
Where(`l.tracker_id = ?`, obj.ID)
labels, cursor = label.QueryWithCursor(ctx, tx, query, cursor)
return nil
}); err != nil {
return nil, err
}
return &model.LabelCursor{labels, cursor}, nil
}
func (r *trackerResolver) Acls(ctx context.Context, obj *model.Tracker, cursor *coremodel.Cursor) (*model.ACLCursor, error) {
@ -325,6 +406,9 @@ func (r *Resolver) Created() api.CreatedResolver { return &createdResolver{r} }
// Event returns api.EventResolver implementation.
func (r *Resolver) Event() api.EventResolver { return &eventResolver{r} }
// Label returns api.LabelResolver implementation.
func (r *Resolver) Label() api.LabelResolver { return &labelResolver{r} }
// LabelUpdate returns api.LabelUpdateResolver implementation.
func (r *Resolver) LabelUpdate() api.LabelUpdateResolver { return &labelUpdateResolver{r} }
@ -353,6 +437,7 @@ type assignmentResolver struct{ *Resolver }
type commentResolver struct{ *Resolver }
type createdResolver struct{ *Resolver }
type eventResolver struct{ *Resolver }
type labelResolver struct{ *Resolver }
type labelUpdateResolver struct{ *Resolver }
type queryResolver struct{ *Resolver }
type statusChangeResolver struct{ *Resolver }

View File

@ -0,0 +1,224 @@
// Code generated by github.com/vektah/dataloaden, DO NOT EDIT.
package loaders
import (
"sync"
"time"
"git.sr.ht/~sircmpwn/todo.sr.ht/api/graph/model"
)
// LabelsByIDLoaderConfig captures the config to create a new LabelsByIDLoader
type LabelsByIDLoaderConfig struct {
// Fetch is a method that provides the data for the loader
Fetch func(keys []int) ([]*model.Label, []error)
// Wait is how long wait before sending a batch
Wait time.Duration
// MaxBatch will limit the maximum number of keys to send in one batch, 0 = not limit
MaxBatch int
}
// NewLabelsByIDLoader creates a new LabelsByIDLoader given a fetch, wait, and maxBatch
func NewLabelsByIDLoader(config LabelsByIDLoaderConfig) *LabelsByIDLoader {
return &LabelsByIDLoader{
fetch: config.Fetch,
wait: config.Wait,
maxBatch: config.MaxBatch,
}
}
// LabelsByIDLoader batches and caches requests
type LabelsByIDLoader struct {
// this method provides the data for the loader
fetch func(keys []int) ([]*model.Label, []error)
// how long to done before sending a batch
wait time.Duration
// this will limit the maximum number of keys to send in one batch, 0 = no limit
maxBatch int
// INTERNAL
// lazily created cache
cache map[int]*model.Label
// the current batch. keys will continue to be collected until timeout is hit,
// then everything will be sent to the fetch method and out to the listeners
batch *labelsByIDLoaderBatch
// mutex to prevent races
mu sync.Mutex
}
type labelsByIDLoaderBatch struct {
keys []int
data []*model.Label
error []error
closing bool
done chan struct{}
}
// Load a Label by key, batching and caching will be applied automatically
func (l *LabelsByIDLoader) Load(key int) (*model.Label, error) {
return l.LoadThunk(key)()
}
// LoadThunk returns a function that when called will block waiting for a Label.
// This method should be used if you want one goroutine to make requests to many
// different data loaders without blocking until the thunk is called.
func (l *LabelsByIDLoader) LoadThunk(key int) func() (*model.Label, error) {
l.mu.Lock()
if it, ok := l.cache[key]; ok {
l.mu.Unlock()
return func() (*model.Label, error) {
return it, nil
}
}
if l.batch == nil {
l.batch = &labelsByIDLoaderBatch{done: make(chan struct{})}
}
batch := l.batch
pos := batch.keyIndex(l, key)
l.mu.Unlock()
return func() (*model.Label, error) {
<-batch.done
var data *model.Label
if pos < len(batch.data) {
data = batch.data[pos]
}
var err error
// its convenient to be able to return a single error for everything
if len(batch.error) == 1 {
err = batch.error[0]
} else if batch.error != nil {
err = batch.error[pos]
}
if err == nil {
l.mu.Lock()
l.unsafeSet(key, data)
l.mu.Unlock()
}
return data, err
}
}
// LoadAll fetches many keys at once. It will be broken into appropriate sized
// sub batches depending on how the loader is configured
func (l *LabelsByIDLoader) LoadAll(keys []int) ([]*model.Label, []error) {
results := make([]func() (*model.Label, error), len(keys))
for i, key := range keys {
results[i] = l.LoadThunk(key)
}
labels := make([]*model.Label, len(keys))
errors := make([]error, len(keys))
for i, thunk := range results {
labels[i], errors[i] = thunk()
}
return labels, errors
}
// LoadAllThunk returns a function that when called will block waiting for a Labels.
// This method should be used if you want one goroutine to make requests to many
// different data loaders without blocking until the thunk is called.
func (l *LabelsByIDLoader) LoadAllThunk(keys []int) func() ([]*model.Label, []error) {
results := make([]func() (*model.Label, error), len(keys))
for i, key := range keys {
results[i] = l.LoadThunk(key)
}
return func() ([]*model.Label, []error) {
labels := make([]*model.Label, len(keys))
errors := make([]error, len(keys))
for i, thunk := range results {
labels[i], errors[i] = thunk()
}
return labels, errors
}
}
// Prime the cache with the provided key and value. If the key already exists, no change is made
// and false is returned.
// (To forcefully prime the cache, clear the key first with loader.clear(key).prime(key, value).)
func (l *LabelsByIDLoader) Prime(key int, value *model.Label) bool {
l.mu.Lock()
var found bool
if _, found = l.cache[key]; !found {
// make a copy when writing to the cache, its easy to pass a pointer in from a loop var
// and end up with the whole cache pointing to the same value.
cpy := *value
l.unsafeSet(key, &cpy)
}
l.mu.Unlock()
return !found
}
// Clear the value at key from the cache, if it exists
func (l *LabelsByIDLoader) Clear(key int) {
l.mu.Lock()
delete(l.cache, key)
l.mu.Unlock()
}
func (l *LabelsByIDLoader) unsafeSet(key int, value *model.Label) {
if l.cache == nil {
l.cache = map[int]*model.Label{}
}
l.cache[key] = value
}
// keyIndex will return the location of the key in the batch, if its not found
// it will add the key to the batch
func (b *labelsByIDLoaderBatch) keyIndex(l *LabelsByIDLoader, key int) int {
for i, existingKey := range b.keys {
if key == existingKey {
return i
}
}
pos := len(b.keys)
b.keys = append(b.keys, key)
if pos == 0 {
go b.startTimer(l)
}
if l.maxBatch != 0 && pos >= l.maxBatch-1 {
if !b.closing {
b.closing = true
l.batch = nil
go b.end(l)
}
}
return pos
}
func (b *labelsByIDLoaderBatch) startTimer(l *LabelsByIDLoader) {
time.Sleep(l.wait)
l.mu.Lock()
// we must have hit a batch limit and are already finalizing this batch
if b.closing {
l.mu.Unlock()
return
}
l.batch = nil
l.mu.Unlock()
b.end(l)
}
func (b *labelsByIDLoaderBatch) end(l *LabelsByIDLoader) {
b.data, b.error = l.fetch(b.keys)
close(b.done)
}

View File

@ -5,9 +5,10 @@ package loaders
//go:generate ./gen TrackersByIDLoader int api/graph/model.Tracker
//go:generate ./gen TrackersByNameLoader string api/graph/model.Tracker
//go:generate ./gen TrackersByOwnerNameLoader [2]string api/graph/model.Tracker
//go:generate ./gen CommentsByIDLoader int api/graph/model.Comment
//go:generate ./gen TicketsByIDLoader int api/graph/model.Ticket
//go:generate ./gen CommentsByIDLoader int api/graph/model.Comment
//go:generate go run github.com/vektah/dataloaden ParticipantsByIDLoader int git.sr.ht/~sircmpwn/todo.sr.ht/api/graph/model.Entity
//go:generate ./gen LabelsByIDLoader int api/graph/model.Label
import (
"context"
@ -40,6 +41,7 @@ type Loaders struct {
TicketsByID TicketsByIDLoader
CommentsByID CommentsByIDLoader
ParticipantsByID ParticipantsByIDLoader
LabelsByID LabelsByIDLoader
}
func fetchUsersByID(ctx context.Context) func(ids []int) ([]*model.User, []error) {
@ -522,6 +524,65 @@ func fetchParticipantsByID(ctx context.Context) func(ids []int) ([]model.Entity,
}
}
func fetchLabelsByID(ctx context.Context) func(ids []int) ([]*model.Label, []error) {
return func(ids []int) ([]*model.Label, []error) {
labels := make([]*model.Label, len(ids))
if err := database.WithTx(ctx, &sql.TxOptions{
Isolation: 0,
ReadOnly: true,
}, func (tx *sql.Tx) error {
var (
err error
rows *sql.Rows
)
auser := auth.ForContext(ctx)
query := database.
Select(ctx, (&model.Label{}).As(`l`)).
From(`"label" l`).
Join(`"tracker" tr ON tr.id = l.tracker_id`).
LeftJoin(`user_access ua ON ua.tracker_id = tr.id`).
Where(sq.And{
sq.Expr(`l.id = ANY(?)`, pq.Array(ids)),
sq.Or{
sq.Expr(`tr.owner_id = ?`, auser.UserID),
sq.Expr(`tr.default_user_perms > 0`),
sq.And{
sq.Expr(`ua.user_id = ?`, auser.UserID),
sq.Expr(`ua.permissions > 0`),
},
},
})
if rows, err = query.RunWith(tx).QueryContext(ctx); err != nil {
return err
}
defer rows.Close()
labelsByID := map[int]*model.Label{}
for rows.Next() {
label := model.Label{}
if err := rows.Scan(database.Scan(ctx, &label)...); err != nil {
return err
}
labelsByID[label.ID] = &label
}
if err = rows.Err(); err != nil {
return err
}
for i, id := range ids {
labels[i] = labelsByID[id]
}
return nil
}); err != nil {
panic(err)
}
return labels, nil
}
}
func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), loadersCtxKey, &Loaders{
@ -565,6 +626,11 @@ func Middleware(next http.Handler) http.Handler {
wait: 1 * time.Millisecond,
fetch: fetchParticipantsByID(r.Context()),
},
LabelsByID: LabelsByIDLoader{
maxBatch: 100,
wait: 1 * time.Millisecond,
fetch: fetchLabelsByID(r.Context()),
},
})
r = r.WithContext(ctx)
next.ServeHTTP(w, r)