Basic API works.

This commit is contained in:
2020-05-08 15:54:40 +02:00
parent 6837e7b4c8
commit 564ac0d24a
36 changed files with 1450 additions and 80 deletions
+14 -5
View File
@@ -1,7 +1,9 @@
package graph
import (
"git.aiterp.net/stufflog/server/database"
"git.aiterp.net/stufflog/server/graph/graphcore"
"git.aiterp.net/stufflog/server/graph/loaders"
"git.aiterp.net/stufflog/server/graph/resolvers"
"git.aiterp.net/stufflog/server/services"
"github.com/99designs/gqlgen/graphql"
@@ -12,18 +14,25 @@ import (
//go:generate go run github.com/99designs/gqlgen --verbose --config gqlgen.yml
// New creates a new GraphQL schema.
func New(s services.Bundle) graphql.ExecutableSchema {
func New(bundle services.Bundle, database database.Database) graphql.ExecutableSchema {
return graphcore.NewExecutableSchema(graphcore.Config{
Resolvers: &resolvers.Resolver{S: s},
Resolvers: &resolvers.Resolver{
Bundle: bundle,
Database: database,
},
})
}
func Gin(s services.Bundle) gin.HandlerFunc {
schema := New(s)
func Gin(bundle services.Bundle, database database.Database) gin.HandlerFunc {
schema := New(bundle, database)
gqlHandler := handler.NewDefaultServer(schema)
return func(c *gin.Context) {
s.Auth.CheckGinSession(c)
bundle.Auth.CheckGinSession(c)
c.Request = c.Request.WithContext(
loaders.NewUserLoaderContext(c.Request.Context(), database.Users()),
)
gqlHandler.ServeHTTP(c.Writer, c.Request)
}
+2
View File
@@ -0,0 +1,2 @@
// Package graphcore contains the generated code.
package graphcore
+19
View File
@@ -0,0 +1,19 @@
package graphutil
import (
"context"
"github.com/99designs/gqlgen/graphql"
)
func SelectsAnyField(ctx context.Context, fields ...string) bool {
collectedFields := graphql.CollectFieldsCtx(ctx, []string{"description"})
for _, collectedField := range collectedFields {
for _, field := range fields {
if collectedField.Name == field {
return true
}
}
}
return false
}
+2
View File
@@ -0,0 +1,2 @@
// Package loaders is for the generated data loaders.
package loaders
@@ -0,0 +1,224 @@
// Code generated by github.com/vektah/dataloaden, DO NOT EDIT.
package loaders
import (
"sync"
"time"
"git.aiterp.net/stufflog/server/models"
)
// ProjectPermissionLoaderConfig captures the config to create a new ProjectPermissionLoader
type ProjectPermissionLoaderConfig struct {
// Fetch is a method that provides the data for the loader
Fetch func(keys []string) ([]*models.ProjectPermission, []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
}
// NewProjectPermissionLoader creates a new ProjectPermissionLoader given a fetch, wait, and maxBatch
func NewProjectPermissionLoader(config ProjectPermissionLoaderConfig) *ProjectPermissionLoader {
return &ProjectPermissionLoader{
fetch: config.Fetch,
wait: config.Wait,
maxBatch: config.MaxBatch,
}
}
// ProjectPermissionLoader batches and caches requests
type ProjectPermissionLoader struct {
// this method provides the data for the loader
fetch func(keys []string) ([]*models.ProjectPermission, []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[string]*models.ProjectPermission
// 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 *projectPermissionLoaderBatch
// mutex to prevent races
mu sync.Mutex
}
type projectPermissionLoaderBatch struct {
keys []string
data []*models.ProjectPermission
error []error
closing bool
done chan struct{}
}
// Load a ProjectPermission by key, batching and caching will be applied automatically
func (l *ProjectPermissionLoader) Load(key string) (*models.ProjectPermission, error) {
return l.LoadThunk(key)()
}
// LoadThunk returns a function that when called will block waiting for a ProjectPermission.
// 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 *ProjectPermissionLoader) LoadThunk(key string) func() (*models.ProjectPermission, error) {
l.mu.Lock()
if it, ok := l.cache[key]; ok {
l.mu.Unlock()
return func() (*models.ProjectPermission, error) {
return it, nil
}
}
if l.batch == nil {
l.batch = &projectPermissionLoaderBatch{done: make(chan struct{})}
}
batch := l.batch
pos := batch.keyIndex(l, key)
l.mu.Unlock()
return func() (*models.ProjectPermission, error) {
<-batch.done
var data *models.ProjectPermission
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 *ProjectPermissionLoader) LoadAll(keys []string) ([]*models.ProjectPermission, []error) {
results := make([]func() (*models.ProjectPermission, error), len(keys))
for i, key := range keys {
results[i] = l.LoadThunk(key)
}
projectPermissions := make([]*models.ProjectPermission, len(keys))
errors := make([]error, len(keys))
for i, thunk := range results {
projectPermissions[i], errors[i] = thunk()
}
return projectPermissions, errors
}
// LoadAllThunk returns a function that when called will block waiting for a ProjectPermissions.
// 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 *ProjectPermissionLoader) LoadAllThunk(keys []string) func() ([]*models.ProjectPermission, []error) {
results := make([]func() (*models.ProjectPermission, error), len(keys))
for i, key := range keys {
results[i] = l.LoadThunk(key)
}
return func() ([]*models.ProjectPermission, []error) {
projectPermissions := make([]*models.ProjectPermission, len(keys))
errors := make([]error, len(keys))
for i, thunk := range results {
projectPermissions[i], errors[i] = thunk()
}
return projectPermissions, 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 *ProjectPermissionLoader) Prime(key string, value *models.ProjectPermission) 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 *ProjectPermissionLoader) Clear(key string) {
l.mu.Lock()
delete(l.cache, key)
l.mu.Unlock()
}
func (l *ProjectPermissionLoader) unsafeSet(key string, value *models.ProjectPermission) {
if l.cache == nil {
l.cache = map[string]*models.ProjectPermission{}
}
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 *projectPermissionLoaderBatch) keyIndex(l *ProjectPermissionLoader, key string) 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 *projectPermissionLoaderBatch) startTimer(l *ProjectPermissionLoader) {
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 *projectPermissionLoaderBatch) end(l *ProjectPermissionLoader) {
b.data, b.error = l.fetch(b.keys)
close(b.done)
}
+57
View File
@@ -0,0 +1,57 @@
package loaders
import (
"context"
"git.aiterp.net/stufflog/server/database/repositories"
"git.aiterp.net/stufflog/server/internal/xlerrors"
"git.aiterp.net/stufflog/server/models"
"time"
)
// go run github.com/vektah/dataloaden UserLoader string *git.aiterp.net/stufflog/server/models.User
var userLoaderCtxKey = "ctx.stufflog.UserLoader"
func NewUserLoaderContext(ctx context.Context, userRepo repositories.UserRepository) context.Context {
return context.WithValue(ctx, userLoaderCtxKey, NewUserLoader(ctx, userRepo))
}
func UserLoaderFromContext(ctx context.Context) *UserLoader {
return ctx.Value(userLoaderCtxKey).(*UserLoader)
}
func NewUserLoader(ctx context.Context, userRepo repositories.UserRepository) *UserLoader {
return &UserLoader{
wait: 2 * time.Millisecond,
maxBatch: 100,
fetch: func(keys []string) ([]*models.User, []error) {
results := make([]*models.User, len(keys))
errors := make([]error, len(keys))
users, err := userRepo.List(ctx, models.UserFilter{UserIDs: keys})
if err != nil {
for i := range errors {
errors[i] = err
}
return results, errors
}
userMap := make(map[string]*models.User, len(users))
for _, user := range users {
userMap[user.ID] = user
}
for i, id := range keys {
user := userMap[id]
if user != nil {
results[i] = user
} else {
errors[i] = xlerrors.NotFound("User")
}
}
return results, errors
},
}
}
+215
View File
@@ -0,0 +1,215 @@
// Code generated by github.com/vektah/dataloaden, DO NOT EDIT.
package loaders
import (
"sync"
"time"
"git.aiterp.net/stufflog/server/models"
)
// UserLoaderConfig captures the config to create a new UserLoader
type UserLoaderConfig struct {
// Fetch is a method that provides the data for the loader
Fetch func(keys []string) ([]*models.User, []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
}
// UserLoader batches and caches requests
type UserLoader struct {
// this method provides the data for the loader
fetch func(keys []string) ([]*models.User, []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[string]*models.User
// 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 *userLoaderBatch
// mutex to prevent races
mu sync.Mutex
}
type userLoaderBatch struct {
keys []string
data []*models.User
error []error
closing bool
done chan struct{}
}
// Load a User by key, batching and caching will be applied automatically
func (l *UserLoader) Load(key string) (*models.User, error) {
return l.LoadThunk(key)()
}
// LoadThunk returns a function that when called will block waiting for a User.
// 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 *UserLoader) LoadThunk(key string) func() (*models.User, error) {
l.mu.Lock()
if it, ok := l.cache[key]; ok {
l.mu.Unlock()
return func() (*models.User, error) {
return it, nil
}
}
if l.batch == nil {
l.batch = &userLoaderBatch{done: make(chan struct{})}
}
batch := l.batch
pos := batch.keyIndex(l, key)
l.mu.Unlock()
return func() (*models.User, error) {
<-batch.done
var data *models.User
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 *UserLoader) LoadAll(keys []string) ([]*models.User, []error) {
results := make([]func() (*models.User, error), len(keys))
for i, key := range keys {
results[i] = l.LoadThunk(key)
}
users := make([]*models.User, len(keys))
errors := make([]error, len(keys))
for i, thunk := range results {
users[i], errors[i] = thunk()
}
return users, errors
}
// LoadAllThunk returns a function that when called will block waiting for a Users.
// 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 *UserLoader) LoadAllThunk(keys []string) func() ([]*models.User, []error) {
results := make([]func() (*models.User, error), len(keys))
for i, key := range keys {
results[i] = l.LoadThunk(key)
}
return func() ([]*models.User, []error) {
users := make([]*models.User, len(keys))
errors := make([]error, len(keys))
for i, thunk := range results {
users[i], errors[i] = thunk()
}
return users, 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 *UserLoader) Prime(key string, value *models.User) 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 *UserLoader) Clear(key string) {
l.mu.Lock()
delete(l.cache, key)
l.mu.Unlock()
}
func (l *UserLoader) unsafeSet(key string, value *models.User) {
if l.cache == nil {
l.cache = map[string]*models.User{}
}
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 *userLoaderBatch) keyIndex(l *UserLoader, key string) 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 *userLoaderBatch) startTimer(l *UserLoader) {
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 *userLoaderBatch) end(l *UserLoader) {
b.data, b.error = l.fetch(b.keys)
close(b.done)
}
+57 -5
View File
@@ -5,22 +5,74 @@ package resolvers
import (
"context"
"fmt"
"git.aiterp.net/stufflog/server/graph/graphcore"
"git.aiterp.net/stufflog/server/graph/graphutil"
"git.aiterp.net/stufflog/server/graph/loaders"
"git.aiterp.net/stufflog/server/internal/xlerrors"
"git.aiterp.net/stufflog/server/models"
)
func (r *issueResolver) Project(ctx context.Context, obj *models.Issue) (*models.Project, error) {
panic(fmt.Errorf("not implemented"))
return r.Database.Projects().Find(ctx, obj.ProjectID)
}
func (r *issueResolver) Owner(ctx context.Context, obj *models.Issue) (*models.User, error) {
panic(fmt.Errorf("not implemented"))
if obj.OwnerID == "" {
return nil, nil
}
// Shortcut: if only ID is needed, resolve with empty user.
if !graphutil.SelectsAnyField(ctx, "name", "active", "admin") {
return &models.User{ID: obj.OwnerID}, nil
}
return loaders.UserLoaderFromContext(ctx).Load(obj.OwnerID)
}
func (r *issueResolver) Assignee(ctx context.Context, obj *models.Issue) (*models.User, error) {
panic(fmt.Errorf("not implemented"))
if obj.AssigneeID == "" {
return nil, nil
}
// Shortcut: if only ID is needed, resolve with empty user.
if !graphutil.SelectsAnyField(ctx, "name", "active", "admin") {
return &models.User{ID: obj.AssigneeID}, nil
}
return loaders.UserLoaderFromContext(ctx).Load(obj.AssigneeID)
}
func (r *issueResolver) Status(ctx context.Context, obj *models.Issue) (*models.ProjectStatus, error) {
// Shortcut: if description isn't needed, resolve this with issue's properties.
if !graphutil.SelectsAnyField(ctx, "description") {
return &models.ProjectStatus{
ProjectID: obj.ProjectID,
Stage: obj.StatusStage,
Name: obj.StatusName,
Description: "FAKE",
}, nil
}
status, err := r.Database.ProjectStatuses().Find(ctx, obj.ProjectID, obj.StatusName)
if xlerrors.IsNotFound(err) {
return &models.ProjectStatus{
ProjectID: obj.ProjectID,
Stage: obj.StatusStage,
Name: obj.StatusName,
Description: "(Deleted or unknown status)",
}, nil
} else if err != nil {
return nil, err
}
// If the stage doesn't match, sneakily correct it for next time.
if status.Stage != obj.StatusStage {
updatedIssue := *obj
updatedIssue.StatusStage = status.Stage
_ = r.Database.Issues().Save(ctx, updatedIssue)
}
return status, nil
}
// Issue returns graphcore.IssueResolver implementation.
+91 -5
View File
@@ -5,18 +5,104 @@ package resolvers
import (
"context"
"fmt"
"errors"
"git.aiterp.net/stufflog/server/graph/graphcore"
"git.aiterp.net/stufflog/server/internal/xlerrors"
"git.aiterp.net/stufflog/server/models"
)
func (r *mutationResolver) LoginUser(ctx context.Context, input *graphcore.UserLoginInput) (*models.User, error) {
panic(fmt.Errorf("not implemented"))
func (r *mutationResolver) CreateProject(ctx context.Context, input graphcore.ProjectCreateInput) (*models.Project, error) {
user := r.Auth.UserFromContext(ctx)
if user == nil {
return nil, xlerrors.PermissionDenied
}
project := &models.Project{
ID: input.ID,
Name: input.Name,
Description: input.Description,
DailyPoints: input.DailyPoints,
}
if !project.ValidKey() {
return nil, errors.New("the project must have a valid ID (only uppercase allowed)")
}
if project.Name == "" || project.Description == "" {
return nil, errors.New("name and description cannot be left empty")
}
project, err := r.Database.Projects().Insert(ctx, *project)
if err != nil {
return nil, err
}
err = r.Database.Projects().SetPermission(ctx, models.ProjectPermission{
ProjectID: project.ID,
UserID: user.ID,
Level: models.ProjectPermissionLevelOwner,
})
return project, nil
}
func (r *mutationResolver) CreateIssue(ctx context.Context, input graphcore.IssueCreateInput) (*models.Issue, error) {
user := r.Auth.UserFromContext(ctx)
if user == nil {
return nil, xlerrors.PermissionDenied
}
project, err := r.Database.Projects().Find(ctx, input.ProjectID)
if err != nil {
return nil, err
}
if perm, err := r.Auth.ProjectPermission(ctx, *project); err != nil || !perm.CanManageOwnIssue() {
return nil, xlerrors.PermissionDenied
}
issue := &models.Issue{
ProjectID: project.ID,
OwnerID: user.ID,
AssigneeID: "",
StatusStage: input.StatusStage,
StatusName: input.StatusName,
Name: input.Name,
Title: input.Name,
Description: input.Description,
}
if input.Title != nil && *input.Title != "" {
issue.Title = *input.Title
}
if input.DueTime != nil && !input.DueTime.IsZero() {
issue.DueTime = *input.DueTime
}
if input.AssigneeID != nil && *input.AssigneeID != "" {
issue.AssigneeID = *input.AssigneeID
}
issue, err = r.Database.Issues().Insert(ctx, *issue)
if err != nil {
return nil, err
}
return issue, nil
}
func (r *mutationResolver) LoginUser(ctx context.Context, input graphcore.UserLoginInput) (*models.User, error) {
return r.Auth.Login(ctx, input.Username, input.Password)
}
func (r *mutationResolver) LogoutUser(ctx context.Context) (*models.User, error) {
panic(fmt.Errorf("not implemented"))
return r.Auth.Logout(ctx)
}
func (r *mutationResolver) CreateUser(ctx context.Context, input graphcore.UserCreateInput) (*models.User, error) {
active := input.Active == nil || *input.Active
admin := input.Admin != nil && *input.Admin
return r.Auth.CreateUser(ctx, input.Username, input.Password, input.Name, active, admin)
}
func (r *mutationResolver) EditUser(ctx context.Context, input graphcore.UserEditInput) (*models.User, error) {
return r.Auth.EditUser(ctx, input.Username, input.SetName, input.CurrentPassword, input.SetPassword)
}
// Mutation returns graphcore.MutationResolver implementation.
+41 -6
View File
@@ -5,25 +5,60 @@ package resolvers
import (
"context"
"fmt"
"git.aiterp.net/stufflog/server/graph/graphcore"
"git.aiterp.net/stufflog/server/graph/loaders"
"git.aiterp.net/stufflog/server/internal/xlerrors"
"git.aiterp.net/stufflog/server/models"
)
func (r *projectResolver) Issues(ctx context.Context, obj *models.Project, filter *graphcore.ProjectIssueFilter) ([]*models.Issue, error) {
panic(fmt.Errorf("not implemented"))
if filter == nil {
filter = &graphcore.ProjectIssueFilter{}
}
return r.Database.Issues().List(ctx, models.IssueFilter{
ProjectIDs: []string{obj.ID},
AssigneeIDs: filter.AssigneeIds,
Search: filter.Search,
MinStage: filter.MinStage,
MaxStage: filter.MaxStage,
Limit: filter.Limit,
})
}
func (r *projectResolver) Permissions(ctx context.Context, obj *models.Project) ([]*graphcore.ProjectPermissions, error) {
panic(fmt.Errorf("not implemented"))
func (r *projectResolver) Permissions(ctx context.Context, obj *models.Project) ([]*models.ProjectPermission, error) {
if perm, err := r.Auth.ProjectPermission(ctx, *obj); err != nil || !perm.CanManagePermissions() {
return nil, xlerrors.PermissionDenied
}
return r.Database.Projects().ListPermissions(ctx, *obj)
}
func (r *projectResolver) UserPermissions(ctx context.Context, obj *models.Project) (*graphcore.ProjectPermissions, error) {
panic(fmt.Errorf("not implemented"))
func (r *projectResolver) UserPermissions(ctx context.Context, obj *models.Project) (*models.ProjectPermission, error) {
return r.Auth.ProjectPermission(ctx, *obj)
}
func (r *projectResolver) Statuses(ctx context.Context, obj *models.Project, filter *models.ProjectStatusFilter) ([]*models.ProjectStatus, error) {
if filter == nil {
filter = &models.ProjectStatusFilter{}
}
filter.ProjectID = &obj.ID
return r.Database.ProjectStatuses().List(ctx, *filter)
}
func (r *projectPermissionResolver) User(ctx context.Context, obj *models.ProjectPermission) (*models.User, error) {
return loaders.UserLoaderFromContext(ctx).Load(obj.UserID)
}
// Project returns graphcore.ProjectResolver implementation.
func (r *Resolver) Project() graphcore.ProjectResolver { return &projectResolver{r} }
// ProjectPermission returns graphcore.ProjectPermissionResolver implementation.
func (r *Resolver) ProjectPermission() graphcore.ProjectPermissionResolver {
return &projectPermissionResolver{r}
}
type projectResolver struct{ *Resolver }
type projectPermissionResolver struct{ *Resolver }
+98 -6
View File
@@ -5,30 +5,122 @@ package resolvers
import (
"context"
"fmt"
"errors"
"git.aiterp.net/stufflog/server/graph/graphcore"
"git.aiterp.net/stufflog/server/models"
"git.aiterp.net/stufflog/server/services"
)
func (r *queryResolver) Issue(ctx context.Context, id string) (*models.Issue, error) {
panic(fmt.Errorf("not implemented"))
user := r.Auth.UserFromContext(ctx)
if user == nil {
return nil, services.ErrPermissionDenied
}
issue, err := r.Database.Issues().Find(ctx, id)
if err != nil {
return nil, err
}
_, err = r.Auth.IssuePermission(ctx, *issue)
if err != nil {
return nil, err
}
return issue, nil
}
func (r *queryResolver) Issues(ctx context.Context, filter *models.IssueFilter) ([]*models.Issue, error) {
panic(fmt.Errorf("not implemented"))
user := r.Auth.UserFromContext(ctx)
if user == nil {
return nil, services.ErrPermissionDenied
}
if filter == nil {
filter = &models.IssueFilter{}
}
issues, err := r.Database.Issues().List(ctx, *filter)
if err != nil {
return nil, err
}
deleteList := make([]int, 0, len(issues))
for i, issue := range issues {
_, err := r.Auth.IssuePermission(ctx, *issue)
if err != nil {
deleteList = append(deleteList, i-len(deleteList))
}
}
for _, index := range deleteList {
issues = append(issues[:index], issues[index+1:]...)
}
return issues, nil
}
func (r *queryResolver) Project(ctx context.Context, id string) (*models.Project, error) {
panic(fmt.Errorf("not implemented"))
user := r.Auth.UserFromContext(ctx)
if user == nil {
return nil, services.ErrPermissionDenied
}
project, err := r.Database.Projects().Find(ctx, id)
if err != nil {
return nil, err
}
_, err = r.Auth.ProjectPermission(ctx, *project)
if err != nil {
return nil, err
}
return project, nil
}
func (r *queryResolver) Projects(ctx context.Context, filter *models.ProjectFilter) ([]*models.Project, error) {
panic(fmt.Errorf("not implemented"))
user := r.Auth.UserFromContext(ctx)
if user == nil {
return nil, services.ErrPermissionDenied
}
skipCheck := false
if filter == nil {
filter = &models.ProjectFilter{}
}
if filter.Permission == nil {
skipCheck = true
filter.Permission = &models.ProjectFilterPermission{
UserID: user.ID,
MinLevel: models.ProjectPermissionLevelObserver,
}
}
projects, err := r.Database.Projects().List(ctx, *filter)
if err != nil {
return nil, err
}
if !skipCheck && len(projects) > 0 {
deleteList := make([]int, 0, 4)
for i, project := range projects {
if _, err := r.Auth.ProjectPermission(ctx, *project); err != nil {
deleteList = append(deleteList, i-len(deleteList))
}
}
for _, di := range deleteList {
projects = append(projects[:di], projects[di:]...)
}
}
return projects, nil
}
func (r *queryResolver) Session(ctx context.Context) (*models.User, error) {
panic(fmt.Errorf("not implemented"))
user := r.Auth.UserFromContext(ctx)
if user == nil {
return nil, errors.New("not logged in")
}
return user, nil
}
// Query returns graphcore.QueryResolver implementation.
+6 -2
View File
@@ -1,11 +1,15 @@
package resolvers
import "git.aiterp.net/stufflog/server/services"
import (
"git.aiterp.net/stufflog/server/database"
"git.aiterp.net/stufflog/server/services"
)
// This file will not be regenerated automatically.
//
// It serves as dependency injection for your app, add any dependencies you require here.
type Resolver struct {
S services.Bundle
services.Bundle
Database database.Database
}
+20 -5
View File
@@ -1,10 +1,5 @@
type Issue {
id: String!
projectId: String!
ownerId: String!
assigneeId: String!
statusStage: Int!
statusName: String!
createdTime: Time!
updatedTime: Time!
dueTime: Time
@@ -15,6 +10,7 @@ type Issue {
project: Project
owner: User
assignee: User
status: ProjectStatus!
}
input IssueFilter {
@@ -34,4 +30,23 @@ input IssueFilter {
maxStage: Int
"Limit the result set"
limit: Int
}
input IssueCreateInput {
"Project ID"
projectId: String!
"Status stage"
statusStage: Int!
"Status name"
statusName: String!
"A name for the issue."
name: String!
"Description of the issue."
description: String!
"Assign this issue, will default to unassigned"
assigneeId: String
"A date when this issue is due"
dueTime: Time
"Optional title to use instead of the name when not in a list."
title: String
}
+16 -1
View File
@@ -1,4 +1,19 @@
type Mutation {
loginUser(input: UserLoginInput): User!
# PROJECT
"Create a new project"
createProject(input: ProjectCreateInput!): Project!
# ISSUE
"Create a new issue"
createIssue(input: IssueCreateInput!): Issue!
# USER
"Log in"
loginUser(input: UserLoginInput!): User!
"Log out"
logoutUser: User!
"Create a new user. This can only be done by administrators."
createUser(input: UserCreateInput!): User!
"Edit an existing user. This can only be done by administrators"
editUser(input: UserEditInput!): User!
}
+24 -6
View File
@@ -11,17 +11,17 @@ type Project {
"Get issues within the project."
issues(filter: ProjectIssueFilter): [Issue!]!
"All users' permissions. Only available to administrators and up."
permissions: [ProjectPermissions!]!
permissions: [ProjectPermission!]!
"Own permissions to the project. Available to any logged in user."
userPermissions: ProjectPermissions!
userPermissions: ProjectPermission!
"List all project statuses."
statuses(filter: ProjectStatusFilter): [ProjectStatus!]!
}
"The permissions of a user within the project."
type ProjectPermissions {
"User ID."
userId: String!
type ProjectPermission {
"Access level."
accessLevel: Int!
level: Int!
"The user whose permissions it is. Can be null if the user no longer exists."
user: User
@@ -67,4 +67,22 @@ input ProjectIssueFilter {
maxStage: Int
"Limit the result set"
limit: Int
}
input ProjectCreateInput {
"The ID of the project, which will be the prefix of all issue keys."
id: String!
"The name of the project, used in place of the ID in the UI."
name: String!
"Describe the project."
description: String!
"Bonus to points goal for any activity being done on a given day."
dailyPoints: Int!
}
input ProjectStatusFilter {
"Minimum stage of the project status to list"
minStage: Int!
"Maximum stage of the project status to list"
maxStage: Int!
}
+18 -2
View File
@@ -12,7 +12,23 @@ type User {
"Input for loginUser."
input UserLoginInput {
userId: String!
username: String!
password: String!
rememberMe: Boolean!
}
input UserCreateInput {
username: String!
password: String!
name: String!
active: Boolean
admin: Boolean
}
input UserEditInput {
username: String!
setName: String
setPassword: String
currentPassword: String
}