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.

42 lines
955 B

  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.Character:
  12. return models.ChangeKey{Model: "Character", ID: v.ID}
  13. case models.Channel:
  14. return models.ChangeKey{Model: "Channel", ID: v.Name}
  15. }
  16. model := ""
  17. if t := reflect.TypeOf(object); t.Kind() == reflect.Ptr {
  18. model = t.Elem().Name()
  19. } else {
  20. model = t.Name()
  21. }
  22. id := ""
  23. v := reflect.ValueOf(object)
  24. for v.Kind() == reflect.Ptr {
  25. v = v.Elem()
  26. }
  27. if f := v.FieldByName("ID"); f.Kind() == reflect.String {
  28. id = f.String()
  29. } else if f = v.FieldByName("Name"); f.Kind() == reflect.String {
  30. id = f.String()
  31. } else {
  32. panic("Unsupported model")
  33. }
  34. return models.ChangeKey{Model: models.ChangeModel(model), ID: id}
  35. }