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 changekeys
  2. import (
  3. "reflect"
  4. "git.aiterp.net/rpdata/api/models"
  5. )
  6. // One makes a ChangeKey for a model, or panics if it's not supported.
  7. func One(object interface{}) models.ChangeKey {
  8. switch v := object.(type) {
  9. case models.Post:
  10. return models.ChangeKey{Model: "Post", ID: v.ID}
  11. case *models.Post:
  12. return models.ChangeKey{Model: "Post", ID: v.ID}
  13. case models.Character:
  14. return models.ChangeKey{Model: "Character", ID: v.ID}
  15. case *models.Character:
  16. return models.ChangeKey{Model: "Character", ID: v.ID}
  17. case models.Channel:
  18. return models.ChangeKey{Model: "Channel", ID: v.Name}
  19. case *models.Channel:
  20. return models.ChangeKey{Model: "Channel", ID: v.Name}
  21. }
  22. model := ""
  23. if t := reflect.TypeOf(object); t.Kind() == reflect.Ptr {
  24. model = t.Elem().Name()
  25. } else {
  26. model = t.Name()
  27. }
  28. id := ""
  29. v := reflect.ValueOf(object)
  30. for v.Kind() == reflect.Ptr {
  31. v = v.Elem()
  32. }
  33. if f := v.FieldByName("ID"); f.Kind() == reflect.String {
  34. id = f.String()
  35. } else if f = v.FieldByName("Name"); f.Kind() == reflect.String {
  36. id = f.String()
  37. } else {
  38. panic("Unsupported model")
  39. }
  40. return models.ChangeKey{Model: models.ChangeModel(model), ID: id}
  41. }