datastore

package
v0.3.5 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2023 License: BSD-3-Clause Imports: 5 Imported by: 0

Documentation

Overview

Package datastore provides a set of tools to interact with Google Cloud Datastore. It abstracts datastore operations such as creating a client, saving, retrieving, updating, and deleting URL entities. It is designed to work with the URL shortener service to manage shortened URLs and their corresponding original URLs.

The package encapsulates the complexity of direct datastore interactions and offers a simplified API for the rest of the application. It also integrates structured logging using the zap library, which allows for consistent and searchable log entries across the service.

Usage example:

func main() {
    logger, _ := zap.NewDevelopment()
    ctx := datastore.CreateContext()
    config := datastore.NewConfig(logger, "my-project-id")
    client, err := datastore.CreateDatastoreClient(ctx, config)
    if err != nil {
        log.Fatalf("Failed to create datastore client: %v", err)
    }
    defer datastore.CloseClient(client)

    // Use the client to interact with the datastore
    url := &datastore.URL{Original: "https://example.com", ID: "abc123"}
    if err := datastore.SaveURL(ctx, client, url); err != nil {
        log.Fatalf("Failed to save URL: %v", err)
    }

    // Retrieve, update, or delete URLs as needed
}

The package also defines a custom `URL` type that represents a URL entity within the datastore. This type is used for all operations that involve URL entities.

The `Client` type wraps the Google Cloud Datastore client, providing a layer of abstraction that allows for mocking and testing without relying on an actual datastore instance.

The `NewConfig` function creates a new `Config` instance, which holds the configuration settings for the datastore client, including the logger and project ID.

The `CreateDatastoreClient` function now requires a `Config` object instead of a project ID string, reflecting a more structured approach to configuration.

The `SetLogger` function allows for the injection of a zap logger instance, which is used throughout the package to log operations and errors. This ensures that any issues or actions are logged in a format that is consistent with the rest of the URL shortener service.

Error handling is a critical aspect of the package. The `ErrNotFound` variable is returned when a requested entity is not found in the datastore, allowing calling code to distinguish between different types of errors and handle them accordingly.

The package functions are designed to be used in a concurrent environment and are safe for use by multiple goroutines.

The `CreateContext` function is provided to create a new context for datastore operations, which can be used to control the lifetime of requests and to pass cancellation signals and other request-scoped values across API boundaries.

It is important to close the datastore client when it is no longer needed by calling the `CloseClient` function to release any resources associated with the client.

Copyright (c) 2023 H0llyW00dzZ

Index

Constants

View Source
const (
	DataStoreNosuchentity         = "datastore: no such entity"
	DataStoreFailedtoCreateClient = "Failed to create client"
	DataStoreFailedtoSaveURL      = "Failed to save URL"
	DataStoreFailedtoGetURL       = "Failed to get URL"
	DataStoreFailedtoUpdateURL    = "Failed to update URL"
	DataStoreFailedtoDeleteURL    = "Failed to delete URL"
	DataStoreFailedToCloseClient  = "Failed to close client"

	// DataStoreNameKey is the name of the Kind in Datastore for URL entities.
	// Defining it here enables changing the Kind name in one place if needed.
	DataStoreNameKey = "urlz"

	// URL Info Messages
	InfoAttemptingToUpdateURLInDatastore = "Attempting to update URL in Datastore"
	InfoFailedToUpdateURLInDatastore     = "Failed to update URL in Datastore"
	InfoUpdateSuccessful                 = "URL updated successfully in the datastore"
)

Define datastore constants. This is used to identify the component that is logging the message. Easy Maintenance: If the error message changes, it only need to change it in one place.

Variables

ErrNotFound is the error returned when a requested entity is not found in the datastore.

View Source
var Logger *zap.Logger

Logger is a package-level variable to access the zap logger throughout the datastore package. It is intended to be used by other functions within the package for logging purposes.

Functions

func CloseClient

func CloseClient(client *Client) error

CloseClient closes the Datastore client. It should be called to clean up resources and connections when the client is no longer needed. Returns an error if the client could not be closed.

func CreateContext

func CreateContext() context.Context

CreateContext creates a new context that can be used for Datastore operations. It returns a non-nil, empty context.

func DeleteURL added in v0.1.10

func DeleteURL(ctx context.Context, client *Client, id string) error

DeleteURL deletes a URL entity by its ID from Datastore. It requires a context, a Datastore client, and the ID of the URL entity. Returns an error if the entity could not be deleted.

func SaveURL

func SaveURL(ctx context.Context, client *Client, url *URL) error

SaveURL saves a new URL entity to Datastore under the Kind 'urlz'. It takes a context, a Datastore client, and a URL struct. If the Kind 'urlz' does not exist, Datastore will create it automatically. Returns an error if the URL entity could not be saved.

func SetLogger added in v0.1.7

func SetLogger(logger *zap.Logger)

SetLogger sets the logger instance for the package.

func UpdateURL added in v0.1.9

func UpdateURL(ctx context.Context, client *Client, id string, newURL string) error

UpdateURL updates an existing URL entity in Datastore with a new URL. It requires a context, a Datastore client, the ID of the URL entity, and the new URL to update. Returns an error if the URL entity could not be updated.

Types

type Client added in v0.1.5

type Client struct {
	*cloudDatastore.Client
}

Client wraps the cloudDatastore.Client to abstract away the underlying implementation.

func CreateDatastoreClient

func CreateDatastoreClient(ctx context.Context, config *Config) (*Client, error)

CreateDatastoreClient creates a new client connected to Google Cloud Datastore. It requires a context and a Config struct to initialize the connection. It returns a new Datastore client wrapped in a custom Client type or an error if the connection could not be established.

type Config added in v0.2.4

type Config struct {
	Logger    *zap.Logger
	ProjectID string
}

Config holds the configuration settings for the datastore client.

func NewConfig added in v0.2.4

func NewConfig(logger *zap.Logger, projectID string) *Config

NewConfig creates a new instance of Config with the given logger and project ID.

type URL

type URL struct {
	Original string `datastore:"original"` // The original URL.
	ID       string `datastore:"id"`       // The unique identifier for the shortened URL.
}

URL represents a shortened URL with its original URL and a unique identifier.

func GetURL

func GetURL(ctx context.Context, dsClient *Client, id string) (*URL, error)

GetURL retrieves a URL entity by its ID from Datastore. It requires a context, a Datastore client, and the ID of the URL entity. Returns the URL entity or an error if the entity could not be retrieved.

Jump to

Keyboard shortcuts

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