63 lines
1.5 KiB
Go
63 lines
1.5 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
"github.com/vingarcia/ksql"
|
|
)
|
|
|
|
func (d *Database) FindOrCreateProduct(system string, barcode string) (*Product, error) {
|
|
product, err := d.FindProductByBarcode(system, barcode)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// If the product doesn't exist yet, create it
|
|
if product == nil {
|
|
product, err = d.CreateProduct(system, barcode)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
return product, nil
|
|
}
|
|
|
|
// FindProductByBarcode will return nil with no error if the product doesn't exist.
|
|
func (d *Database) FindProductByBarcode(system string, barcode string) (*Product, error) {
|
|
|
|
ctx := context.Background()
|
|
|
|
var product Product
|
|
err := d.db.QueryOne(ctx, &product, "FROM products WHERE system = $1 AND barcode = $2", system, barcode)
|
|
|
|
// No error because product may just not exist.
|
|
if err == ksql.ErrRecordNotFound {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &product, nil
|
|
}
|
|
|
|
// CreateProduct simply makes an entry in the products table. Prefer FindOrCreateProduct
|
|
func (d *Database) CreateProduct(system string, barcode string) (*Product, error) {
|
|
ctx := context.Background()
|
|
var product = Product{
|
|
System: system,
|
|
Barcode: barcode,
|
|
Created_at: time.Now(),
|
|
}
|
|
|
|
log.Debugf("successfully created new product: %v", product)
|
|
|
|
if err := d.db.Insert(ctx, ProductsTable, &product); err != nil {
|
|
return nil, fmt.Errorf("failed to insert new product: %w", err)
|
|
}
|
|
|
|
return &product, nil
|
|
}
|