Capstone/ui/db/vendors.go

56 lines
1.5 KiB
Go
Raw Normal View History

2023-10-31 21:31:26 -04:00
package db
import (
"context"
"fmt"
"net/http"
"time"
2023-10-31 21:31:26 -04:00
"git.preston-baxter.com/Preston_PLB/capstone/frontend-service/config"
"git.preston-baxter.com/Preston_PLB/capstone/frontend-service/db/models"
"go.mongodb.org/mongo-driver/bson"
2023-11-02 19:23:07 -04:00
"go.mongodb.org/mongo-driver/bson/primitive"
2023-11-02 21:06:35 -04:00
"go.mongodb.org/mongo-driver/mongo"
2023-10-31 21:31:26 -04:00
"go.mongodb.org/mongo-driver/mongo/options"
)
2023-11-02 19:23:07 -04:00
func (db *DB) FindVendorAccountByUser(userId primitive.ObjectID) ([]models.VendorAccount, error) {
2023-10-31 21:31:26 -04:00
conf := config.Config()
opts := options.Find()
res, err := db.client.Database(conf.Mongo.EntDb).Collection(conf.Mongo.EntCol).Find(context.Background(), bson.M{"user_id": userId, "obj_info.ent": models.VENDOR_ACCOUNT_TYPE}, opts)
if err != nil {
2023-11-02 21:06:35 -04:00
if err == mongo.ErrNoDocuments {
return nil, nil
}
2023-10-31 21:31:26 -04:00
return nil, err
}
vendors := []models.VendorAccount{}
2023-11-02 19:23:07 -04:00
err = res.All(context.Background(), &vendors)
2023-10-31 21:31:26 -04:00
if err != nil {
return nil, err
}
return vendors, nil
}
//Make
func (db *DB) MakeRequestWithAccount(req *http.Request, va *models.VendorAccount) (*http.Response, error) {
//make new credential and save new credentials to DB
if va.OauthCredentials.ExpiresAt.Before(time.Now()) {
err := va.OauthCredentials.RefreshAccessToken(va.Name)
if err != nil {
return nil, err
}
err = db.SaveModel(va)
if err != nil {
return nil, err
}
}
client := http.Client{}
req.Header.Add("Authorization", fmt.Sprintf("%s: %s", va.OauthCredentials.TokenType, va.OauthCredentials.AccessToken))
return client.Do(req)
}