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.

75 lines
1.9 KiB

  1. package queries
  2. import (
  3. "context"
  4. "errors"
  5. "time"
  6. "git.aiterp.net/rpdata/api/models/characters"
  7. "git.aiterp.net/rpdata/api/models/changekeys"
  8. "git.aiterp.net/rpdata/api/models/changes"
  9. "git.aiterp.net/rpdata/api/graph2/input"
  10. "git.aiterp.net/rpdata/api/internal/auth"
  11. "git.aiterp.net/rpdata/api/models/chapters"
  12. "git.aiterp.net/rpdata/api/models/comments"
  13. "git.aiterp.net/rpdata/api/models"
  14. )
  15. // Queries
  16. func (r *resolver) Comment(ctx context.Context, id string) (models.Comment, error) {
  17. return comments.Find(id)
  18. }
  19. // Mutations
  20. func (r *mutationResolver) AddComment(ctx context.Context, input input.CommentAddInput) (models.Comment, error) {
  21. chapter, err := chapters.FindID(input.ChapterID)
  22. if err != nil {
  23. return models.Comment{}, errors.New("Chapter not found")
  24. }
  25. token := auth.TokenFromContext(ctx)
  26. if !token.Permitted("member", "story.edit") {
  27. return models.Comment{}, errors.New("Unauthorized")
  28. }
  29. if !chapter.CanComment() {
  30. return models.Comment{}, errors.New("You cannot comment on this chapter")
  31. }
  32. var characterPtr *models.Character
  33. if input.CharacterID != nil {
  34. character, err := characters.FindID(*input.CharacterID)
  35. if err != nil {
  36. return models.Comment{}, errors.New("Character not found")
  37. } else if character.Author != token.UserID {
  38. return models.Comment{}, errors.New("That is not your character")
  39. }
  40. characterPtr = &character
  41. }
  42. fictionalDate := time.Time{}
  43. if input.FictionalDate != nil {
  44. fictionalDate = *input.FictionalDate
  45. }
  46. subject := ""
  47. if input.Subject != nil {
  48. subject = *input.Subject
  49. }
  50. comment, err := comments.Add(chapter, subject, token.UserID, input.Source, input.CharacterName, characterPtr, time.Now(), fictionalDate)
  51. if err != nil {
  52. return models.Comment{}, errors.New("Failed to add comment: " + err.Error())
  53. }
  54. go changes.Submit("Comment", "add", token.UserID, true, changekeys.Many(comment, chapter, models.Story{ID: chapter.StoryID}), comment)
  55. return comment, nil
  56. }