db

package
v0.0.0-...-e158c48 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 3, 2025 License: AGPL-3.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const DBNameChars = "abcdefghijklmnopqrstuvwxyz"

DBNameChars is the set of characters used by RandomDatabaseName.

View Source
const DBNameLen = 15

DBNameLen is the length of a database name generated by RandomDatabaseName.

View Source
const (
	// DatabaseName is the name of the MongoDB database.
	DatabaseName = "emprius-backend"
)

Variables

This section is empty.

Functions

func InitializeDatabase

func InitializeDatabase(db *Database) error

InitializeDatabase sets up the database with default data and ensures collections are ready for use.

func RandomDatabaseName

func RandomDatabaseName() string

RandomDatabaseName generates a random valid MongoDB database name.

func SanitizeString

func SanitizeString(s string) string

SanitizeString removes all non-alphanumeric characters from a string, except for commas, dots, minus signs, and underscores.

func StartMongoContainer

func StartMongoContainer(ctx context.Context) (testcontainers.Container, error)

StartMongoContainer creates and starts an instance of the MongoDB container.

func WithinCircumference

func WithinCircumference(point1, point2 Location, distance int) bool

WithinCircumference calculates if two Location points are within the same geographic circumference of diameter equal to the specified distance. The function takes in three arguments: - location1: a Location struct with latitude and longitude in microdegrees (1e-6 degrees) - location2: a Location struct with latitude and longitude in microdegrees (1e-6 degrees) - distance: an integer representing the diameter of the circumference in meters The function returns a boolean value indicating whether the two Location points are within the same circumference of diameter equal to the distance.

Types

type Booking

type Booking struct {
	ID            primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`
	ToolID        primitive.ObjectID `bson:"toolId" json:"toolId"`
	FromUserID    primitive.ObjectID `bson:"fromUserId" json:"fromUserId"`
	ToUserID      primitive.ObjectID `bson:"toUserId" json:"toUserId"`
	StartDate     time.Time          `bson:"startDate" json:"startDate"`
	EndDate       time.Time          `bson:"endDate" json:"endDate"`
	Contact       string             `bson:"contact" json:"contact"`
	Comments      string             `bson:"comments" json:"comments"`
	BookingStatus BookingStatus      `bson:"bookingStatus" json:"bookingStatus"`
	CreatedAt     time.Time          `bson:"createdAt" json:"createdAt"`
	UpdatedAt     time.Time          `bson:"updatedAt" json:"updatedAt"`
}

Booking represents a tool booking in the system

type BookingService

type BookingService struct {
	// contains filtered or unexported fields
}

BookingService handles all booking related database operations

func NewBookingService

func NewBookingService(db *mongo.Database) *BookingService

NewBookingService creates a new BookingService instance

func (*BookingService) Create

func (s *BookingService) Create(
	ctx context.Context,
	req *CreateBookingRequest,
	fromUserID, toUserID primitive.ObjectID,
) (*Booking, error)

Create creates a new booking

func (*BookingService) Get

Get retrieves a booking by ID

func (*BookingService) GetPendingRatings

func (s *BookingService) GetPendingRatings(ctx context.Context, userID primitive.ObjectID) ([]*Booking, error)

GetPendingRatings gets bookings that need to be rated by the user

func (*BookingService) GetUserPetitions

func (s *BookingService) GetUserPetitions(ctx context.Context, userID primitive.ObjectID) ([]*Booking, error)

GetUserPetitions gets all bookings made by the user

func (*BookingService) GetUserRequests

func (s *BookingService) GetUserRequests(ctx context.Context, userID primitive.ObjectID) ([]*Booking, error)

GetUserRequests gets all booking requests for tools owned by the user

func (*BookingService) UpdateStatus

func (s *BookingService) UpdateStatus(ctx context.Context, id primitive.ObjectID, status BookingStatus) error

UpdateStatus updates the booking status

type BookingStatus

type BookingStatus string

BookingStatus represents the current state of a booking

const (
	BookingStatusPending  BookingStatus = "PENDING"
	BookingStatusAccepted BookingStatus = "ACCEPTED"
	BookingStatusRejected BookingStatus = "REJECTED"
	BookingStatusReturned BookingStatus = "RETURNED"
)

type CreateBookingRequest

type CreateBookingRequest struct {
	ToolID    primitive.ObjectID `bson:"toolId" json:"toolId"`
	StartDate time.Time          `bson:"startDate" json:"startDate"`
	EndDate   time.Time          `bson:"endDate" json:"endDate"`
	Contact   string             `bson:"contact" json:"contact"`
	Comments  string             `bson:"comments" json:"comments"`
}

CreateBookingRequest represents the request to create a new booking

type Database

type Database struct {
	Client              *mongo.Client
	Database            *mongo.Database
	ToolService         *ToolService
	ToolCategoryService *ToolCategoryService
	ImageService        *ImageService
	TransportService    *TransportService
	UserService         *UserService
	BookingService      *BookingService
}

Database struct encapsulates MongoDB client and database.

func New

func New(uri string) (*Database, error)

New initializes a new MongoDB connection.

func (*Database) Close

func (db *Database) Close(ctx context.Context) error

Close disconnects the MongoDB client.

func (*Database) CreateTables

func (db *Database) CreateTables() error

CreateTables initializes all collections and indexes.

type DateRange

type DateRange struct {
	From uint32 `bson:"from" json:"from"`
	To   uint32 `bson:"to" json:"to"`
}

DateRange represents a range of dates using UNIX time format.

type Image

type Image struct {
	Hash    types.HexBytes `bson:"hash" json:"hash"`
	Name    string         `bson:"name" json:"name"`
	Content []byte         `bson:"content" json:"content,omitempty"`
	Link    string         `bson:"link" json:"link,omitempty"`
}

Image represents the schema for the "images" collection.

type ImageService

type ImageService struct {
	Collection *mongo.Collection
}

ImageService provides methods to interact with the "images" collection.

func NewImageService

func NewImageService(db *Database) *ImageService

NewImageService creates a new ImageService.

func (*ImageService) GetAllImages

func (s *ImageService) GetAllImages(ctx context.Context) ([]*Image, error)

GetAllImages retrieves all Image documents.

func (*ImageService) GetImage

func (s *ImageService) GetImage(ctx context.Context, hash []byte) (*Image, error)

GetImage retrieves an Image by its hash.

func (*ImageService) InsertImage

func (s *ImageService) InsertImage(ctx context.Context, image *Image) (*mongo.InsertOneResult, error)

InsertImage inserts a new Image document.

type Location

type Location struct {
	Latitude  int64 `bson:"latitude" json:"latitude"`
	Longitude int64 `bson:"longitude" json:"longitude"`
}

Location represents a geographical location in microdegrees.

func NewLocation

func NewLocation(start Location, distanceNorthKm, distanceEastKm float64) Location

NewLocation creates a new location that is a certain distance (in kilometers) north and east from a starting location. The distance is approximated using a simple flat Earth model, which is reasonably accurate for small distances (up to a few hundred kilometers).

type SearchToolsOptions

type SearchToolsOptions struct {
	Categories []int
	MayBeFree  *bool
	MaxCost    *uint64
	Distance   int
	Location   *Location
}

SearchToolsOptions represents the search criteria for tools.

type Tool

type Tool struct {
	ID               int64       `bson:"_id" json:"id"`
	Title            string      `bson:"title" json:"title"`
	Description      string      `bson:"description" json:"description"`
	IsAvailable      bool        `bson:"isAvailable" json:"isAvailable"`
	MayBeFree        bool        `bson:"mayBeFree" json:"mayBeFree"`
	AskWithFee       bool        `bson:"askWithFee" json:"askWithFee"`
	Cost             uint64      `bson:"cost" json:"cost"`
	UserID           string      `bson:"userId" json:"userId"`
	Images           []Image     `bson:"images" json:"images"`
	TransportOptions []Transport `bson:"transportOptions" json:"transportOptions"`
	ToolCategory     int         `bson:"toolCategory" json:"toolCategory"`
	Location         Location    `bson:"location" json:"location"`
	Rating           int32       `bson:"rating" json:"rating"`
	EstimatedValue   uint64      `bson:"estimatedValue" json:"estimatedValue"`
	Height           uint32      `bson:"height" json:"height"`
	Weight           uint32      `bson:"weight" json:"weight"`
	ReservedDates    []DateRange `bson:"reservedDates" json:"reservedDates"`
}

Tool represents the schema for the "tools" collection.

type ToolCategory

type ToolCategory struct {
	ID   int    `bson:"id" json:"id"`
	Name string `bson:"name" json:"name"`
}

ToolCategory represents the schema for the "tool_categories" collection.

type ToolCategoryService

type ToolCategoryService struct {
	Collection *mongo.Collection
}

ToolCategoryService provides methods to interact with the "tool_categories" collection.

func NewToolCategoryService

func NewToolCategoryService(db *Database) *ToolCategoryService

NewToolCategoryService creates a new ToolCategoryService.

func (*ToolCategoryService) GetAllToolCategories

func (s *ToolCategoryService) GetAllToolCategories(ctx context.Context) ([]*ToolCategory, error)

GetAllToolCategories retrieves all ToolCategory documents.

func (*ToolCategoryService) GetToolCategoryByID

func (s *ToolCategoryService) GetToolCategoryByID(ctx context.Context, id int) (*ToolCategory, error)

GetToolCategoryByID retrieves a ToolCategory by its ID.

func (*ToolCategoryService) InitializeDefaultCategories

func (s *ToolCategoryService) InitializeDefaultCategories(ctx context.Context, defaultCategories []string) error

InitializeDefaultCategories ensures the default tool categories exist in the collection.

func (*ToolCategoryService) InsertToolCategory

func (s *ToolCategoryService) InsertToolCategory(ctx context.Context, category *ToolCategory) (*mongo.InsertOneResult, error)

InsertToolCategory inserts a new ToolCategory document.

type ToolService

type ToolService struct {
	Collection *mongo.Collection
}

ToolService provides methods to interact with the "tools" collection.

func NewToolService

func NewToolService(db *Database) *ToolService

NewToolService creates a new ToolService.

func (*ToolService) CountTools

func (s *ToolService) CountTools(ctx context.Context) (int64, error)

CountTools returns the total number of tools.

func (*ToolService) GetAllTools

func (s *ToolService) GetAllTools(ctx context.Context) ([]*Tool, error)

GetAllTools retrieves all Tool documents.

func (*ToolService) GetToolByID

func (s *ToolService) GetToolByID(ctx context.Context, id int64) (*Tool, error)

GetToolByID retrieves a Tool by its ID.

func (*ToolService) GetToolsByUserID

func (s *ToolService) GetToolsByUserID(ctx context.Context, userID string) ([]*Tool, error)

GetToolsByUserID retrieves all tools owned by a specific user.

func (*ToolService) InsertTool

func (s *ToolService) InsertTool(ctx context.Context, tool *Tool) (*mongo.InsertOneResult, error)

InsertTool inserts a new Tool document.

func (*ToolService) SearchTools

func (s *ToolService) SearchTools(ctx context.Context, opts SearchToolsOptions) ([]*Tool, error)

SearchTools searches for tools based on various criteria.

func (*ToolService) SearchToolsByLocation

func (s *ToolService) SearchToolsByLocation(ctx context.Context, location Location, radiusMeters int) ([]*Tool, error)

SearchToolsByLocation retrieves tools within a specified radius (in meters) from a given location.

func (*ToolService) UpdateTool

func (s *ToolService) UpdateTool(ctx context.Context, id int64, update bson.M) (*mongo.UpdateResult, error)

UpdateTool updates a Tool document by ID.

func (*ToolService) UpdateToolFields

func (s *ToolService) UpdateToolFields(ctx context.Context, id int64, updates map[string]interface{}) error

UpdateToolFields updates specific fields of a tool.

type Transport

type Transport struct {
	ID   int64  `bson:"id" json:"id"`
	Name string `bson:"name" json:"name"`
}

Transport represents the schema for the "transports" collection.

type TransportService

type TransportService struct {
	Collection *mongo.Collection
}

TransportService provides methods to interact with the "transports" collection.

func NewTransportService

func NewTransportService(db *Database) *TransportService

NewTransportService creates a new TransportService.

func (*TransportService) GetAllTransports

func (s *TransportService) GetAllTransports(ctx context.Context) ([]*Transport, error)

GetAllTransports retrieves all Transport documents.

func (*TransportService) GetTransportByID

func (s *TransportService) GetTransportByID(ctx context.Context, id int64) (*Transport, error)

GetTransportByID retrieves a Transport by its ID.

func (*TransportService) InsertTransport

func (s *TransportService) InsertTransport(ctx context.Context, transport *Transport) (*mongo.InsertOneResult, error)

InsertTransport inserts a new Transport document.

type User

type User struct {
	ID         primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`
	Email      string             `bson:"email" json:"email"`
	Name       string             `bson:"name" json:"name"`
	Community  string             `bson:"community,omitempty" json:"community,omitempty"`
	Password   []byte             `bson:"password" json:"-"` // Don't include password in JSON
	Tokens     uint64             `bson:"tokens" json:"tokens" default:"1000"`
	Active     bool               `bson:"active" json:"active" default:"true"`
	Rating     int32              `bson:"rating" json:"rating" default:"50"`
	AvatarHash types.HexBytes     `bson:"avatarHash,omitempty" json:"avatarHash,omitempty"`
	Location   Location           `bson:"location" json:"location"`
	Verified   bool               `bson:"verified" json:"verified" default:"false"`
}

User represents the schema for the "users" collection.

func (*User) Validate

func (u *User) Validate() error

Validate checks if the user data meets the required constraints

type UserService

type UserService struct {
	Collection *mongo.Collection
}

UserService provides methods to interact with the "users" collection.

func NewUserService

func NewUserService(db *Database) *UserService

NewUserService creates a new UserService.

func (*UserService) CountUsers

func (s *UserService) CountUsers(ctx context.Context) (int64, error)

CountUsers returns the total number of users.

func (*UserService) DeleteUser

func (s *UserService) DeleteUser(ctx context.Context, id primitive.ObjectID) (*mongo.DeleteResult, error)

DeleteUser deletes a User document by their ID.

func (*UserService) GetAllUsers

func (s *UserService) GetAllUsers(ctx context.Context) ([]*User, error)

GetAllUsers retrieves all User documents.

func (*UserService) GetUserByEmail

func (s *UserService) GetUserByEmail(ctx context.Context, email string) (*User, error)

GetUserByEmail retrieves a User by their email address.

func (*UserService) GetUserByID

func (s *UserService) GetUserByID(ctx context.Context, id primitive.ObjectID) (*User, error)

GetUserByID retrieves a User by their ID.

func (*UserService) InsertUser

func (s *UserService) InsertUser(ctx context.Context, user *User) (*mongo.InsertOneResult, error)

InsertUser inserts a new User document.

func (*UserService) UpdateUser

func (s *UserService) UpdateUser(ctx context.Context, id primitive.ObjectID, update bson.M) (*mongo.UpdateResult, error)

UpdateUser updates a User document by their ID.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL