osf

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: May 16, 2022 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package osf provides a client for using the Open Science Framework (OSF, https://osf.io) API. Since this client uses generics in its implementation, Go v1.18+ is required.

This project follows the similar structure of github.com/google/go-github.

Usage:

import (
	"github.com/joshuabezaleel/go-osf"
	"golang.org/x/oauth2"
)

func main() {
	ctx := context.Background()
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: "... your access token ..."},
	)
	tc := oauth2.NewClient(ctx, ts)

	client := osf.NewClient(tc)

	// ...
}

The OSF API token can be obtained from https://osf.io/settings/tokens.

Response Schema

OSF API conforms the JSON API spec v1.0 (https://jsonapi.org/format/1.0/). The response payload will be in this generic form:

type Data[T any, U any] struct {
	Type string  `json:"type"`
	ID   *string `json:"id,omitempty"`

	Attributes    T             `json:"attributes,omitempty"`
	Links         U             `json:"links,omitempty"`
	Relationships Relationships `json:"relationships,omitempty"`
}

type SinglePayload[T any, U any] struct {
	Data   *Data[T, U] `json:"data,omitempty"`
	Errors Errors      `json:"errors,omitempty"`
}

type ManyPayload[T any, U any] struct {
	Data            []*Data[T, U]    `json:"data"`
	PaginationLinks *PaginationLinks `json:"links"`
	Errors          Errors           `json:"errors,omitempty"`

	PaginationMeta  *PaginationMeta `json:"-"`
}

Nearly all methods will be in this form:

t, res, err := client.Service.Method(ctx, ...)
// t is of type T
// res if of type SinglePayload[T,U] or ManyPayload[T,U]

For most of the times, you won't need the res object, as the first returned param should already incorporate Attributes, Links, and Relationships. An exception would be for pagination, which will be explained below.

Pagination

For methods returning multiple objects, the `res` will be of type ManyPayload[T,U]. and PaginationMeta field will contain the pagination info.

total := 0
opts := &osf.PreprintsListOptions{
	ListOptions: osf.ListOptions{
		Page:    1,
		PerPage: 10,
	},
}

for total < 100 {
	preprints, res, err := client.Preprints.ListPreprints(ctx, opts)
	if err != nil {
		log.Fatal(err)
	}

	for _, preprint := range preprints {
		// Do something with preprint
	}

	total += res.PaginationMeta.PerPage
	if total >= res.PaginationMeta.Total {
		break
	}

	opts.Page = res.PaginationMeta.Page+1
}

Error Handling

You may check the error returned for type *Errors, which contains more verbose information about the error.

t, _, err := client.Service.Method(ctx, ...)

if err != nil {
	if errs, ok := err.(*osf.Errors); ok {
		// Handle errs
	} else {
		// Handle err as usual
	}
}

Index

Constants

View Source
const (
	TypePreprints         = "preprints"
	TypeProviders         = "providers"
	TypePreprintProviders = "preprint_providers"
	TypeFiles             = "files"
)

Variables

View Source
var (
	// For HasDataLinks and HasPreregLinks.
	Available     = StringPointer("available")
	No            = StringPointer("no")
	NotApplicable = StringPointer("not_applicable")
)

Functions

func BoolPointer

func BoolPointer(b bool) *bool

func StringPointer

func StringPointer(s string) *string

Types

type Client

type Client struct {
	BaseURL *url.URL

	UserAgent string

	Preprints         *PreprintsService
	PreprintProviders *PreprintProvidersService
	Files             *FilesService
	// contains filtered or unexported fields
}

func NewClient

func NewClient(httpClient *http.Client) *Client

func (*Client) Client

func (c *Client) Client() *http.Client

func (*Client) NewRequest

func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)

type Data

type Data[T any, U any] struct {
	Type string  `json:"type"`
	ID   *string `json:"id,omitempty"`

	Attributes    T             `json:"attributes,omitempty"`
	Links         U             `json:"links,omitempty"`
	Relationships Relationships `json:"relationships,omitempty"`
}

type Error

type Error struct {
	Source *ErrorSource `json:"source,omitempty"`
	Detail string       `json:"detail"`
}

func (*Error) Error

func (e *Error) Error() string

type ErrorSource

type ErrorSource struct {
	Pointer string `json:"pointer"`
}

type Errors

type Errors []*Error

func (Errors) Error

func (e Errors) Error() string

type File

type File struct {
	ID string `json:"id"`

	Kind                  string `json:"kind"`
	Name                  string `json:"name"`
	LastTouched           *Time  `json:"last_touched"`
	MaterializedPath      string `json:"materialized_path"`
	DateModified          string `json:"date_modified"`
	CurrentVersion        int64  `json:"current_version"`
	DeleteAllowed         bool   `json:"delete_allowed"`
	DateCreated           *Time  `json:"date_created"`
	Provider              string `json:"provider"`
	Path                  string `json:"path"`
	CurrentUserCanComment bool   `json:"current_user_can_comment"`
	GUID                  string `json:"guid"`
	// Checkout Checkout `json:"checkout"`
	// Tags [][]Tags `json:"tags"`
	Size int64 `json:"size"`

	FileLinks *FileLinks `json:"-"`
}
type FileLinks struct {
	NewFolder *string `json:"new_folder"`
	Move      *string `json:"move"`
	Upload    *string `json:"upload"`
	Download  *string `json:"download"`
	Delete    *string `json:"delete"`
}

FileLinks contains properties inside the link struct that is related to file endpoints according to the Waterbutler API convention.

type FilesService

type FilesService service

func (*FilesService) DownloadFile

func (s *FilesService) DownloadFile(ctx context.Context, dir string, filename string, file *File) error

func (*FilesService) GetFileByID

func (s *FilesService) GetFileByID(ctx context.Context, id string) (*File, *SinglePayload[*File, *FileLinks], error)
type Link struct {
	Href string `json:"href"`
	Meta Meta   `json:"meta,omitempty"`
}

https://jsonapi.org/format/#document-links

type Links struct {
	Self    *Link `json:"self,omitempty"`
	Related *Link `json:"related,omitempty"`
}

type ListOptions

type ListOptions struct {
	Page    int `url:"page[number],omitempty"`
	PerPage int `url:"page[size],omitempty"`

	Filter map[string]string `url:"-"`
}

type ManyPayload

type ManyPayload[T any, U any] struct {
	Data            []*Data[T, U]    `json:"data"`
	PaginationLinks *PaginationLinks `json:"links"`
	Errors          Errors           `json:"errors,omitempty"`

	PaginationMeta *PaginationMeta `json:"-"`
	// contains filtered or unexported fields
}

func (*ManyPayload[T, U]) TransformedData added in v0.0.3

func (s *ManyPayload[T, U]) TransformedData() []T

type Meta

type Meta map[string]interface{}
type PaginationLinks struct {
	First *string         `json:"first"`
	Last  *string         `json:"last"`
	Prev  *string         `json:"prev"`
	Next  *string         `json:"next"`
	Meta  *PaginationMeta `json:"meta"`
}

type PaginationMeta

type PaginationMeta struct {
	Total   int `json:"total"`
	PerPage int `json:"per_page"`
	Page    int `json:"-"`
}

type Preprint

type Preprint struct {
	ID string `json:"id"`

	DateCreated                 *Time                  `json:"date_created"`
	DateModified                *Time                  `json:"date_modified"`
	DatePublished               *Time                  `json:"date_published"`
	OriginalPublicationDate     *Time                  `json:"original_publication_date"`
	DOI                         *string                `json:"doi"`
	Title                       string                 `json:"title"`
	Description                 string                 `json:"description"`
	IsPublished                 bool                   `json:"is_published"`
	IsPreprintOrphan            bool                   `json:"is_preprint_orphan"`
	LicenseRecord               *PreprintLicenseRecord `json:"license_record"`
	Tags                        []string               `json:"tags"`
	PreprintDOICreated          *Time                  `json:"preprint_doi_created"`
	DateWithdrawn               *Time                  `json:"date_withdrawn"`
	Public                      bool                   `json:"public"`
	ReviewsState                string                 `json:"reviews_state"`
	DateLastTransitioned        *Time                  `json:"date_last_transitioned"`
	HasCOI                      bool                   `json:"has_coi"`
	ConflictOfInterestStatement *string                `json:"conflict_of_interest_statement"`
	Subjects                    [][]*Subject           `json:"subjects"`
	HasDataLinks                *string                `json:"has_data_links"`
	WhyNoData                   *string                `json:"why_no_data"`
	DataLinks                   []string               `json:"data_links"`
	HasPreregLinks              *string                `json:"has_prereg_links"`
	WhyNoPrereg                 *string                `json:"why_no_prereg"`
	PreregLinks                 []string               `json:"prereg_links"`
	PreregLinkInfo              *string                `json:"prereg_link_info"`
	CurrentUserPermissions      []string               `json:"current_user_permissions"`

	Links *PreprintLinks `json:"links"`
}

type PreprintLicenseRecord

type PreprintLicenseRecord struct {
	CopyrightHolders []string `json:"copyright_holders"`
	Year             string   `json:"year"`
}
type PreprintLinks struct {
	Self        *string `json:"self"`
	Html        *string `json:"html"`
	PreprintDOI *string `json:"preprint_doi"`
}

type PreprintProvider

type PreprintProvider struct {
	ID string `json:"id"`

	Name                    string                     `json:"name"`
	Description             string                     `json:"description"`
	AdvisoryBoard           *string                    `json:"advisory_board"`
	Example                 *string                    `json:"example"`
	Domain                  *string                    `json:"domain"`
	DomainRedirectEnabled   bool                       `json:"domain_redirect_enabled"`
	FooterLinks             *string                    `json:"footer_links"`
	EmailSupport            *string                    `json:"email_support"`
	FacebookAppID           *int64                     `json:"facebook_app_id"`
	AllowSubmissions        bool                       `json:"allow_submissions"`
	AllowCommenting         bool                       `json:"allow_commenting"`
	Assets                  map[string]interface{}     `json:"assets"`
	ShareSource             *string                    `json:"share_source"`
	SharePublishType        *string                    `json:"share_publish_type"`
	Permissions             []string                   `json:"permissions"`
	PreprintWord            *string                    `json:"preprint_word"`
	AdditionalProviders     []string                   `json:"additional_providers"`
	ReviewsWorkflow         *string                    `json:"reviews_workflow"`
	ReviewsCommentPrivate   bool                       `json:"reviews_comment_private"`
	ReviewsCommentAnonymous bool                       `json:"reviews_comment_anonymous"`
	HeaderText              *string                    `json:"header_text"`
	BannerPath              *string                    `json:"banner_path"`
	LogoPath                *string                    `json:"logo_path"`
	EmailContact            *string                    `json:"email_contact"`
	SocialTwitter           *string                    `json:"social_twitter"`
	SocialFacebook          *string                    `json:"social_facebook"`
	SocialInstagram         *string                    `json:"social-instagram"`
	SubjectsAcceptable      []*PreprintProviderSubject `json:"subjects_acceptable"`

	Links *PreprintProviderLinks `json:"links"`
}
type PreprintProviderLinks struct {
	Self        *string `json:"self"`
	Preprints   *string `json:"preprints"`
	ExternalURL *string `json:"external_url"`
}

type PreprintProviderSubject

type PreprintProviderSubject struct {
	TaxonomiesID       []string
	IncludeAllChildren bool
}

func (PreprintProviderSubject) MarshalJSON

func (s PreprintProviderSubject) MarshalJSON() ([]byte, error)

func (*PreprintProviderSubject) UnmarshalJSON

func (s *PreprintProviderSubject) UnmarshalJSON(b []byte) error

type PreprintProvidersListOptions

type PreprintProvidersListOptions struct {
	ListOptions
}

type PreprintProvidersService

type PreprintProvidersService service

func (*PreprintProvidersService) GetPreprintProviderByID

type PreprintRequest

type PreprintRequest struct {
	PreprintProviderID          string                 `json:"-"`
	Title                       *string                `json:"title,omitempty"`
	Description                 *string                `json:"description,omitempty"`
	IsPublished                 *bool                  `json:"is_published,omitempty"`
	Subjects                    *[][]string            `json:"subjects,omitempty"`
	OriginalPublicationDate     *Time                  `json:"original_publication_date,omitempty"`
	DOI                         *string                `json:"doi,omitempty"`
	LicenseRecord               *PreprintLicenseRecord `json:"license_record,omitempty"`
	Tags                        *[]string              `json:"tags,omitempty"`
	PreprintDOICreated          *Time                  `json:"preprint_doi_created,omitempty"`
	Public                      *bool                  `json:"public,omitempty"`
	HasCOI                      *bool                  `json:"has_coi,omitempty"`
	ConflictOfInterestStatement *string                `json:"conflict_of_interest_statement,omitempty"`
	HasDataLinks                *string                `json:"has_data_links,omitempty"`
	WhyNoData                   *string                `json:"why_no_data,omitempty"`
	DataLinks                   *[]string              `json:"data_links,omitempty"`
	HasPreregLinks              *string                `json:"has_prereg_links,omitempty"`
	WhyNoPrereg                 *string                `json:"why_no_prereg,omitempty"`
	PreregLinks                 *[]string              `json:"prereg_links,omitempty"`
}

type PreprintsListOptions

type PreprintsListOptions struct {
	ListOptions
}

type PreprintsService

type PreprintsService service

func (*PreprintsService) CreatePreprint

func (s *PreprintsService) CreatePreprint(ctx context.Context, input *PreprintRequest, primaryFile *os.File) (*Preprint, *SinglePayload[*Preprint, *PreprintLinks], error)

func (*PreprintsService) GetPreprintByID

func (*PreprintsService) GetPreprintPrimaryFileByID

func (s *PreprintsService) GetPreprintPrimaryFileByID(ctx context.Context, id string) (*File, *SinglePayload[*File, *FileLinks], error)

func (*PreprintsService) ListPreprints

func (*PreprintsService) UpdatePreprint

func (s *PreprintsService) UpdatePreprint(ctx context.Context, id string, input *PreprintRequest, relationships Relationships) (*Preprint, *SinglePayload[*Preprint, *PreprintLinks], error)

type Relationship

type Relationship struct {
	Links *Links                          `json:"links,omitempty"`
	Data  *Data[interface{}, interface{}] `json:"data,omitempty"`
	Meta  Meta                            `json:"meta,omitempty"`
}

https://jsonapi.org/format/#document-resource-object-relationships

type Relationships

type Relationships map[string]Relationship

type SinglePayload

type SinglePayload[T any, U any] struct {
	Data   *Data[T, U] `json:"data,omitempty"`
	Errors Errors      `json:"errors,omitempty"`
	// contains filtered or unexported fields
}

func (*SinglePayload[T, U]) TransformedData added in v0.0.3

func (s *SinglePayload[T, U]) TransformedData() T

type Subject

type Subject struct {
	ID   string `json:"id"`
	Text string `json:"text"`
}

type Time

type Time struct {
	time.Time
}

func MustParseTime

func MustParseTime(layout, value string) *Time

func ParseTime

func ParseTime(layout, value string) (*Time, error)

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error

type TransformDataFn added in v0.0.3

type TransformDataFn[T any, U any] func(obj *Data[T, U]) (T, error)

Jump to

Keyboard shortcuts

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