sdk

package
v1.16.0 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2026 License: MIT Imports: 15 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

Instantiation

Example using New:

package main

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

func main() {
    client := sdk.New("http://localhost:26900")
}

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 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")

    headers := sdk.Headers{
        Authorization: "auth-token",
    }

    fileMetadata, err := client.GetFile(context.Background(), "/path/to/file.csv", headers)
    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", sdk.Headers{})
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, sdk.Headers{})
GetFile
fileMetadata, err := client.GetFile(ctx, "/path/to/file.csv", sdk.Headers{})
MarkFilePublished
err := client.MarkFilePublished(ctx, "/path/to/file.csv", sdk.Headers{})

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.

Headers

The Headers struct allows the user to provide an Authorization header if required. This must be set without the "Bearer " prefix as the SDK will automatically add this.

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

View Source
const (
	Authorization string = "Authorization"
	BearerPrefix  string = "Bearer "
)

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 string) *Client

New creates a new instance of Client for the service

func NewWithHealthClient

func NewWithHealthClient(hcCli *health.Client) *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, headers Headers) (*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, headers Headers) 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, headers Headers) (*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, headers Headers) 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, headers Headers) (*files.FileEvent, error)
	DeleteFile(ctx context.Context, filePath string, headers Headers) error
	GetFile(ctx context.Context, filePath string, headers Headers) (*files.StoredRegisteredMetaData, error)
	MarkFilePublished(ctx context.Context, filePath string, headers Headers) error
}

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

type Headers added in v1.16.0

type Headers struct {
	Authorization string
}

func (*Headers) Add added in v1.16.0

func (h *Headers) Add(req *http.Request)

Add adds any provided headers to the request

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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