Capstone/service/vendors/pco/webhooks.go

102 lines
2.4 KiB
Go
Raw Normal View History

2023-11-16 23:05:42 -05:00
package pco
import (
2023-11-18 18:15:13 -05:00
"bytes"
2023-11-16 23:05:42 -05:00
"fmt"
"net/http"
"git.preston-baxter.com/Preston_PLB/capstone/webhook-service/vendors/pco/webhooks"
"github.com/google/jsonapi"
)
2023-11-18 18:15:13 -05:00
//gets all current subscriptions
func (api *PcoApiClient) GetSubscriptions() ([]webhooks.Subscription, error) {
2023-11-16 23:05:42 -05:00
api.Url().Path = "/webhook/v2/subscriptions"
req, err := http.NewRequest(http.MethodGet, api.Url().String(), nil)
if err != nil {
return nil, err
}
resp, err := api.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode > 299 || resp.StatusCode < 200 {
return nil, fmt.Errorf("Failed to retrieve plan with status code: %d", resp.StatusCode)
}
2023-11-18 18:15:13 -05:00
subscriptions, err := jsonapi.UnmarshalManyPayload[webhooks.Subscription](resp.Body)
if err != nil {
return nil, err
}
return subscriptions, nil
}
//Posts subscriptions to PCO api and returns a new list of subscriptions
func (api *PcoApiClient) CreateSubscriptions(subscriptions []webhooks.Subscription) ([]webhooks.Subscription, error) {
api.Url().Path = "/webhook/v2/subscriptions"
body := bytes.NewBuffer([]byte{})
err := jsonapi.MarshalPayload(body, subscriptions)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPost, api.Url().String(), body)
2023-11-16 23:05:42 -05:00
if err != nil {
return nil, err
}
2023-11-18 18:15:13 -05:00
resp, err := api.Do(req)
if err != nil {
return nil, err
2023-11-16 23:05:42 -05:00
}
2023-11-18 18:15:13 -05:00
if resp.StatusCode > 299 || resp.StatusCode < 200 {
return nil, fmt.Errorf("Failed to retrieve plan with status code: %d", resp.StatusCode)
}
2023-11-16 23:05:42 -05:00
2023-11-18 18:15:13 -05:00
new_subscriptions, err := jsonapi.UnmarshalManyPayload[webhooks.Subscription](resp.Body)
if err != nil {
return nil, err
}
return new_subscriptions, nil
}
//Posts subcription to PCO api and updates the subscription at the pointer that was passed to the fuinction with the server response
func (api *PcoApiClient) CreateSubscription(subscription *webhooks.Subscription) (error) {
api.Url().Path = "/webhook/v2/subscriptions"
body := bytes.NewBuffer([]byte{})
err := jsonapi.MarshalPayload(body, subscription)
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, api.Url().String(), body)
if err != nil {
return err
}
resp, err := api.Do(req)
if err != nil {
return err
}
if resp.StatusCode > 299 || resp.StatusCode < 200 {
return fmt.Errorf("Failed to retrieve plan with status code: %d", resp.StatusCode)
}
err = jsonapi.UnmarshalPayload(resp.Body, subscription)
if err != nil {
return err
}
2023-11-16 23:05:42 -05:00
2023-11-18 18:15:13 -05:00
return nil
2023-11-16 23:05:42 -05:00
}