GraphQL API and utilities for the rpdata project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
2.2 KiB

  1. package queries
  2. import (
  3. "context"
  4. "time"
  5. "git.aiterp.net/rpdata/api/graphql/resolver/types"
  6. "git.aiterp.net/rpdata/api/internal/auth"
  7. "git.aiterp.net/rpdata/api/model/story"
  8. )
  9. // StoriesArg is args for stories query
  10. type StoriesArg struct {
  11. Filter *struct {
  12. Author *string
  13. Tags *[]struct {
  14. Kind string
  15. Name string
  16. }
  17. EarliestFictionalDate *string
  18. LatestFictionalDate *string
  19. Category *string
  20. Limit *int32
  21. Open *bool
  22. Unlisted *bool
  23. }
  24. }
  25. // Stories resolves the stories query
  26. func (r *QueryResolver) Stories(ctx context.Context, args *StoriesArg) ([]*types.StoryResolver, error) {
  27. var err error
  28. token := auth.TokenFromContext(ctx)
  29. filter := args.Filter
  30. author := ""
  31. category := ""
  32. tags := make([]story.Tag, 0, 8)
  33. earliest := time.Time{}
  34. latest := time.Time{}
  35. unlisted := false
  36. open := (*bool)(nil)
  37. limit := 0
  38. if filter != nil {
  39. if filter.Author != nil {
  40. author = *filter.Author
  41. }
  42. if filter.Category != nil {
  43. category = *filter.Category
  44. }
  45. if filter.Tags != nil {
  46. for _, tagInput := range *filter.Tags {
  47. tags = append(tags, story.Tag{
  48. Kind: tagInput.Kind,
  49. Name: tagInput.Name,
  50. })
  51. }
  52. }
  53. if filter.EarliestFictionalDate != nil {
  54. earliest, err = time.Parse(time.RFC3339Nano, *filter.EarliestFictionalDate)
  55. if err != nil {
  56. return nil, err
  57. }
  58. }
  59. if filter.LatestFictionalDate != nil {
  60. latest, err = time.Parse(time.RFC3339Nano, *filter.LatestFictionalDate)
  61. if err != nil {
  62. return nil, err
  63. }
  64. }
  65. if filter.Limit != nil {
  66. limit = int(*filter.Limit)
  67. }
  68. unlisted = filter.Unlisted != nil && *filter.Unlisted == true
  69. if unlisted {
  70. if token == nil {
  71. return nil, ErrUnauthorized
  72. }
  73. if author != "" && author != token.UserID && !token.Permitted("story.unlisted") {
  74. return nil, ErrPermissionDenied
  75. }
  76. author = token.UserID
  77. }
  78. open = filter.Open
  79. }
  80. stories, err := story.List(author, category, tags, earliest, latest, unlisted, open, limit)
  81. if err != nil {
  82. return nil, err
  83. }
  84. resolvers := make([]*types.StoryResolver, len(stories))
  85. for i, story := range stories {
  86. resolvers[i] = &types.StoryResolver{S: story}
  87. }
  88. return resolvers, nil
  89. }