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.

82 lines
1.7 KiB

  1. package postgres
  2. import (
  3. "context"
  4. "database/sql"
  5. "git.aiterp.net/rpdata/api/database/postgres/psqlcore"
  6. "git.aiterp.net/rpdata/api/internal/generate"
  7. "git.aiterp.net/rpdata/api/models"
  8. )
  9. type keyRepository struct {
  10. db *sql.DB
  11. insertWithIDs bool
  12. }
  13. func (r *keyRepository) Find(ctx context.Context, id string) (*models.Key, error) {
  14. key, err := psqlcore.New(r.db).SelectKey(ctx, id)
  15. if err != nil {
  16. return nil, err
  17. }
  18. return &models.Key{
  19. ID: key.ID,
  20. Name: key.Name,
  21. User: key.User,
  22. Secret: key.Secret,
  23. }, nil
  24. }
  25. func (r *keyRepository) List(ctx context.Context, filter models.KeyFilter) ([]*models.Key, error) {
  26. var keys []psqlcore.Key
  27. if filter.UserID != nil {
  28. keys2, err := psqlcore.New(r.db).SelectKeysByUser(ctx, *filter.UserID)
  29. if err != nil {
  30. return nil, err
  31. }
  32. keys = keys2
  33. } else {
  34. keys2, err := psqlcore.New(r.db).SelectKeys(ctx)
  35. if err != nil {
  36. return nil, err
  37. }
  38. keys = keys2
  39. }
  40. results := make([]*models.Key, 0, len(keys))
  41. for _, key := range keys {
  42. results = append(results, &models.Key{
  43. ID: key.ID,
  44. Name: key.Name,
  45. User: key.User,
  46. Secret: key.Secret,
  47. })
  48. }
  49. return results, nil
  50. }
  51. func (r *keyRepository) Insert(ctx context.Context, key models.Key) (*models.Key, error) {
  52. if !r.insertWithIDs || len(key.ID) < 4 {
  53. key.ID = generate.KeyID()
  54. }
  55. err := psqlcore.New(r.db).InsertKey(ctx, psqlcore.InsertKeyParams{
  56. ID: key.ID,
  57. Name: key.Name,
  58. UserID: key.User,
  59. Secret: key.Secret,
  60. })
  61. if err != nil {
  62. return nil, err
  63. }
  64. return &key, nil
  65. }
  66. func (r *keyRepository) Delete(ctx context.Context, key models.Key) error {
  67. return psqlcore.New(r.db).DeleteKey(ctx, key.ID)
  68. }