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.

48 lines
1.2 KiB

  1. package characters
  2. import (
  3. "errors"
  4. "strconv"
  5. "strings"
  6. "git.aiterp.net/rpdata/api/internal/counter"
  7. "git.aiterp.net/rpdata/api/models"
  8. )
  9. // Add creates a Character and pushes it to the database. It does some validation
  10. // on nick, name, shortName and author. It will generate a shortname from the first
  11. // name if a blank one is provided.
  12. func Add(nick, name, shortName, author, description string) (models.Character, error) {
  13. if len(nick) < 1 || len(name) < 1 || len(author) < 1 {
  14. return models.Character{}, errors.New("Nick, name, or author name too short or empty")
  15. }
  16. if shortName == "" {
  17. shortName = strings.SplitN(name, " ", 2)[0]
  18. }
  19. char, err := FindNick(nick)
  20. if err == nil && char.ID != "" {
  21. return models.Character{}, errors.New("Nick is occupied")
  22. }
  23. nextID, err := counter.Next("auto_increment", "Character")
  24. if err != nil {
  25. return models.Character{}, err
  26. }
  27. character := models.Character{
  28. ID: "C" + strconv.Itoa(nextID),
  29. Nicks: []string{nick},
  30. Name: name,
  31. ShortName: shortName,
  32. Author: author,
  33. Description: description,
  34. }
  35. err = collection.Insert(character)
  36. if err != nil {
  37. return models.Character{}, err
  38. }
  39. return character, nil
  40. }