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.

38 lines
885 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. if f := v.FieldByName("ID"); f.Kind() == reflect.String {
  25. id = f.String()
  26. } else if f = v.FieldByName("Name"); f.Kind() == reflect.String {
  27. id = f.String()
  28. } else {
  29. panic("Unsupported model")
  30. }
  31. return models.ChangeKey{Model: model, ID: id}
  32. }