sdk

package
v1.15.0 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2025 License: MIT Imports: 16 Imported by: 0

README

dp-files-api SDK

Overview

This SDK provides a client for interacting with the dp-files-api. It is intended to be consumed by services that require endpoints from the dp-files-api. It also provides healthcheck functionality, mocks and structs for easy integration, testing and error handling.

Available client methods

Name Description
Checker Calls the health.Client's Checker method
Health Returns the underlying Healthcheck Client for this API client
URL Returns the URL used by this client
DeleteFile Deletes a file at the specified filePath
CreateFileEvent Creates a new file event in the audit log and returns the created event
GetFile Retrieves the metadata for a file at the specified path
MarkFilePublished Sets the state of a file to PUBLISHED

Note: CreateFileEvent does not support the APIError return type yet.

Instantiation

Note: An auth token is required to instantiate the client. All SDK methods send requests with this token for authorization.

Example using New:

package main

import "github.com/ONSdigital/dp-files-api/sdk"

func main() {
    client := sdk.New("http://localhost:26900", "example-auth-token")
}

Example using NewWithHealthClient:

package main

import (
    "github.com/ONSdigital/dp-api-clients-go/v2/health"
    "github.com/ONSdigital/dp-files-api/sdk"
)

func main() {
    existingHealthClient := health.NewClient("existing-service-name", "http://localhost:8080")

    client := sdk.NewWithHealthClient(existingHealthClient, "example-auth-token")
}

Example usage of client

This example demonstrates how the GetFile() function could be used:

package main

import (
    "context"

    "github.com/ONSdigital/dp-files-api/sdk"
)

func main() {
    client := sdk.New("http://localhost:26900", "example-auth-token")

    fileMetadata, err := client.GetFile(context.Background(), "/path/to/file.csv")
    if err != nil {
        // Distinguish between API errors and other errors
        apiErr, ok := err.(*sdk.APIError)
        if ok {
            // Type is *sdk.APIError so we can access all the following fields:
            // apiErr.StatusCode
            // apiErr.Errors // This is an array that can be looped through
            // apiErr.Errors.Error[0].Code
            // apiErr.Errors.Error[0].Description
            // apiErr.Error()
        } else {
            // Handle non-API errors
        }
    }
}

Available Functionality

Checker
import "github.com/ONSdigital/dp-healthcheck/healthcheck"

check := &healthcheck.CheckState{}
err := client.Checker(ctx, check)
Health
healthClient := client.Health()
URL
url := client.URL()
DeleteFile
err := client.DeleteFile(ctx, "/path/to/delete.csv")
CreateFileEvent
import "github.com/ONSdigital/dp-files-api/files"

fileEvent := files.FileEvent{
    RequestedBy: &files.RequestedBy{
        ID:    "user",
        Email: "user@email.com",
    },
    Action:   files.ActionRead,
    Resource: "/path/to/file.csv",
    File: &files.FileMetaData{
        Path: "/path/to/file.csv",
        // Add additional fields
    },
}

createdFileEvent, err := client.CreateFileEvent(ctx, fileEvent)
GetFile
fileMetadata, err := client.GetFile(ctx, "/path/to/file.csv")
MarkFilePublished
err := client.MarkFilePublished(ctx, "/path/to/file.csv")

Additional Information

Errors

The APIError struct allows the user to distinguish if an error is a generic error or an API error, therefore allowing access to more detailed fields. This is shown in the Example usage of client section.

Mocks

To simplify testing, all functions provided by the client have been defined in the Clienter interface. This allows the user to use auto-generated mocks within unit tests.

Example of how to define a mock clienter:

import (
    "context"
    "testing"

    "github.com/ONSdigital/dp-files-api/files"
    "github.com/ONSdigital/dp-files-api/sdk/mocks"
)

func Test(t *testing.T) {
    mockClient := mocks.ClienterMock{
        GetFileFunc: func(ctx context.Context, filePath string) (*files.StoredRegisteredMetaData, error) {
            // Setup mock behaviour here
            return &files.StoredRegisteredMetaData{}, nil
        },
        // Other methods can be mocked if needed
    }
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMissingResponseBody = errors.New("missing response body")
)

List of errors that can be returned by the SDK

Functions

This section is empty.

Types

type APIError added in v1.14.0

type APIError struct {
	StatusCode int
	Errors     *api.JSONErrors
}

APIError represents an error returned by the files API

func (*APIError) Error added in v1.14.0

func (e *APIError) Error() string

Error implements the error interface for APIError

type Client

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

Client is the SDK client for dp-files-api

func New

func New(filesAPIURL, authToken string) *Client

New creates a new instance of Client for the service

func NewWithHealthClient

func NewWithHealthClient(hcCli *health.Client, authToken string) *Client

NewWithHealthClient creates a new instance of Client, reusing the URL and Clienter from the provided health check client

func (*Client) Checker

func (c *Client) Checker(ctx context.Context, check *healthcheck.CheckState) error

Checker Calls the health.Client's Checker method

func (*Client) CreateFileEvent

func (c *Client) CreateFileEvent(ctx context.Context, event files.FileEvent) (*files.FileEvent, error)

CreateFileEvent creates a new file event in the audit log and returns the created event

func (*Client) DeleteFile added in v1.14.0

func (c *Client) DeleteFile(ctx context.Context, filePath string) error

DeleteFile deletes a file at the specified filePath

func (*Client) GetFile added in v1.14.0

func (c *Client) GetFile(ctx context.Context, filePath string) (*files.StoredRegisteredMetaData, error)

GetFile retrieves the metadata for a file at the specified path

func (*Client) Health

func (c *Client) Health() *health.Client

Health returns the underlying Healthcheck Client for this API client

func (*Client) MarkFilePublished added in v1.14.0

func (c *Client) MarkFilePublished(ctx context.Context, filePath string) error

MarkFilePublished makes a PATCH request using patchFile to set the file state to "PUBLISHED"

func (*Client) URL

func (c *Client) URL() string

URL returns the URL used by this client

type Clienter added in v1.14.0

type Clienter interface {
	Checker(ctx context.Context, check *healthcheck.CheckState) error
	Health() *health.Client
	URL() string

	CreateFileEvent(ctx context.Context, event files.FileEvent) (*files.FileEvent, error)
	DeleteFile(ctx context.Context, filePath string) error
	GetFile(ctx context.Context, filePath string) (*files.StoredRegisteredMetaData, error)
	MarkFilePublished(ctx context.Context, filePath string) error
}

type Error

type Error struct {
	Code        string `json:"code"`
	Description string `json:"description"`
}

Error represents a single error in the error response

type ErrorResponse

type ErrorResponse struct {
	Errors []Error `json:"errors"`
}

ErrorResponse represents an error response from the API

type FilePatchRequest added in v1.14.0

type FilePatchRequest struct {
	api.StateMetadata
	ETag string `json:"etag,omitempty"`
}

FilePatchRequest represents the request payload for a PATCH request to "/files/{path:.*}" It includes StateMetadata and an optional ETag as some handlers require it

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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