diff --git a/CHANGELOG.md b/CHANGELOG.md index 054031a1..cf2b1e45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Change Log +## v7.6.0 + +* Breaking: `Domains.GetZone` returns the zone file as `*string` +* Breaking: `BackupArchive.Size` and `StartedAt` are pointers, nil until set +* Breaking: `BackupRestoration.StartedAt` is `*string` and `Options` is `interface{}` +* Added: `Analytics` service with property CRUD, `CreateEvent` and `ListMetrics` +* Added: `Avatars.UpdatePhoto` and `Avatars.DeletePhoto` with the `Account` model +* Added: `Project.UpdateOAuth2Webflow` and the `OAuth2Webflow` model +* Added: `WithCreatePushChannelId` and `WithUpdatePushChannelId` on `Messaging` +* Added: `WithCreateEmailPasswordSessionDuration` and `WithDeleteSessionsCurrent` on `Account` +* Added: Optional `Total` on list methods in `Account`, `Locale`, `Functions`, `Sites` and transactions +* Fixed: Uploads send the endpoint's HTTP method instead of always `POST` +* Fixed: `Decode()` works on models returned by uploads + ## v7.5.0 * Added: OAuth2 token introspection with `Oauth2.Introspect` and the `Oauth2Introspection` response model diff --git a/account/account.go b/account/account.go index 5b44c390..23dce436 100644 --- a/account/account.go +++ b/account/account.go @@ -1836,11 +1836,37 @@ func (srv *Account) UpdateRecoveryOTP(UserId string, Secret string, Password str } +type ListSessionsOptions struct { + Total bool + enabledSetters map[string]bool +} + +func (options ListSessionsOptions) New() *ListSessionsOptions { + options.enabledSetters = map[string]bool{"Total": false} + return &options +} + +type ListSessionsOption func(*ListSessionsOptions) + +func (srv *Account) WithListSessionsTotal(v bool) ListSessionsOption { + return func(o *ListSessionsOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} + // ListSessions get the list of active sessions across different devices for // the currently logged in user. -func (srv *Account) ListSessions() (*models.SessionList, error) { +func (srv *Account) ListSessions(optionalSetters ...ListSessionsOption) (*models.SessionList, error) { path := "/account/sessions" + options := ListSessionsOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } params := map[string]interface{}{} + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" @@ -1873,11 +1899,38 @@ func (srv *Account) ListSessions() (*models.SessionList, error) { } +type DeleteSessionsOptions struct { + Current bool + enabledSetters map[string]bool +} + +func (options DeleteSessionsOptions) New() *DeleteSessionsOptions { + options.enabledSetters = map[string]bool{"Current": false} + return &options +} + +type DeleteSessionsOption func(*DeleteSessionsOptions) + +func (srv *Account) WithDeleteSessionsCurrent(v bool) DeleteSessionsOption { + return func(o *DeleteSessionsOptions) { + o.Current = v + o.enabledSetters["Current"] = true + } +} + // DeleteSessions delete all sessions from the user account and remove any -// sessions cookies from the end client. -func (srv *Account) DeleteSessions() (*interface{}, error) { +// sessions cookies from the end client. Pass `current` as false to keep the +// session making the request and sign out of every other session. +func (srv *Account) DeleteSessions(optionalSetters ...DeleteSessionsOption) (*interface{}, error) { path := "/account/sessions" + options := DeleteSessionsOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } params := map[string]interface{}{} + if options.enabledSetters["Current"] { + params["current"] = options.Current + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["content-type"] = "application/json" @@ -1953,18 +2006,47 @@ func (srv *Account) CreateAnonymousSession() (*models.Session, error) { } +type CreateEmailPasswordSessionOptions struct { + Duration int + enabledSetters map[string]bool +} + +func (options CreateEmailPasswordSessionOptions) New() *CreateEmailPasswordSessionOptions { + options.enabledSetters = map[string]bool{"Duration": false} + return &options +} + +type CreateEmailPasswordSessionOption func(*CreateEmailPasswordSessionOptions) + +func (srv *Account) WithCreateEmailPasswordSessionDuration(v int) CreateEmailPasswordSessionOption { + return func(o *CreateEmailPasswordSessionOptions) { + o.Duration = v + o.enabledSetters["Duration"] = true + } +} + // CreateEmailPasswordSession allow the user to login into their account by // providing a valid email and password combination. This route will create a -// new session for the user. +// new session for the user. Use the optional `duration` parameter to create a +// shorter session, for example when the user doesn't choose "remember me". It +// must be at least 60 seconds and cannot exceed the project maximum session +// length. // // A user is limited to 10 active sessions at a time by default. [Learn more // about session // limits](https://appwrite.io/docs/authentication-security#limits). -func (srv *Account) CreateEmailPasswordSession(Email string, Password string) (*models.Session, error) { +func (srv *Account) CreateEmailPasswordSession(Email string, Password string, optionalSetters ...CreateEmailPasswordSessionOption) (*models.Session, error) { path := "/account/sessions/email" + options := CreateEmailPasswordSessionOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } params := map[string]interface{}{} params["email"] = Email params["password"] = Password + if options.enabledSetters["Duration"] { + params["duration"] = options.Duration + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["content-type"] = "application/json" diff --git a/analytics/analytics.go b/analytics/analytics.go new file mode 100644 index 00000000..851a54de --- /dev/null +++ b/analytics/analytics.go @@ -0,0 +1,711 @@ +package analytics + +import ( + "encoding/json" + "errors" + "strings" + + "github.com/appwrite/sdk-for-go/v7/client" + "github.com/appwrite/sdk-for-go/v7/models" +) + +// Analytics service +type Analytics struct { + client client.Client +} + +func New(clt client.Client) *Analytics { + return &Analytics{ + client: clt, + } +} + +type ListPropertiesOptions struct { + Queries []string + Search string + Total bool + enabledSetters map[string]bool +} + +func (options ListPropertiesOptions) New() *ListPropertiesOptions { + options.enabledSetters = map[string]bool{"Queries": false, "Search": false, "Total": false} + return &options +} + +type ListPropertiesOption func(*ListPropertiesOptions) + +func (srv *Analytics) WithListPropertiesQueries(v []string) ListPropertiesOption { + return func(o *ListPropertiesOptions) { + o.Queries = v + o.enabledSetters["Queries"] = true + } +} +func (srv *Analytics) WithListPropertiesSearch(v string) ListPropertiesOption { + return func(o *ListPropertiesOptions) { + o.Search = v + o.enabledSetters["Search"] = true + } +} +func (srv *Analytics) WithListPropertiesTotal(v bool) ListPropertiesOption { + return func(o *ListPropertiesOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} + +// ListProperties list analytics properties for the current project. +func (srv *Analytics) ListProperties(optionalSetters ...ListPropertiesOption) (*models.AnalyticsPropertyList, error) { + path := "/analytics/properties" + options := ListPropertiesOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } + params := map[string]interface{}{} + if options.enabledSetters["Queries"] { + params["queries"] = options.Queries + } + if options.enabledSetters["Search"] { + params["search"] = options.Search + } + if options.enabledSetters["Total"] { + params["total"] = options.Total + } + headers := map[string]interface{}{} + headers["X-Appwrite-Project"] = srv.client.Config["project"] + headers["accept"] = "application/json" + + resp, err := srv.client.Call("GET", path, headers, params) + if err != nil { + return nil, err + } + if strings.HasPrefix(resp.Type, "application/json") { + bytes, err := client.ResponseBody(resp) + if err != nil { + return nil, err + } + + parsed := models.AnalyticsPropertyList{}.New(bytes) + + err = json.Unmarshal(bytes, parsed) + if err != nil { + return nil, err + } + + return parsed, nil + } + var parsed models.AnalyticsPropertyList + parsed, ok := resp.Result.(models.AnalyticsPropertyList) + if !ok { + return nil, errors.New("unexpected response type") + } + return &parsed, nil + +} + +type CreatePropertyOptions struct { + Domain string + Timezone string + Enabled bool + Public bool + AllowedOrigins []string + enabledSetters map[string]bool +} + +func (options CreatePropertyOptions) New() *CreatePropertyOptions { + options.enabledSetters = map[string]bool{"Domain": false, "Timezone": false, "Enabled": false, "Public": false, "AllowedOrigins": false} + return &options +} + +type CreatePropertyOption func(*CreatePropertyOptions) + +func (srv *Analytics) WithCreatePropertyDomain(v string) CreatePropertyOption { + return func(o *CreatePropertyOptions) { + o.Domain = v + o.enabledSetters["Domain"] = true + } +} +func (srv *Analytics) WithCreatePropertyTimezone(v string) CreatePropertyOption { + return func(o *CreatePropertyOptions) { + o.Timezone = v + o.enabledSetters["Timezone"] = true + } +} +func (srv *Analytics) WithCreatePropertyEnabled(v bool) CreatePropertyOption { + return func(o *CreatePropertyOptions) { + o.Enabled = v + o.enabledSetters["Enabled"] = true + } +} +func (srv *Analytics) WithCreatePropertyPublic(v bool) CreatePropertyOption { + return func(o *CreatePropertyOptions) { + o.Public = v + o.enabledSetters["Public"] = true + } +} +func (srv *Analytics) WithCreatePropertyAllowedOrigins(v []string) CreatePropertyOption { + return func(o *CreatePropertyOptions) { + o.AllowedOrigins = v + o.enabledSetters["AllowedOrigins"] = true + } +} + +// CreateProperty create a new analytics property to track a website or +// application. +func (srv *Analytics) CreateProperty(PropertyId string, Name string, optionalSetters ...CreatePropertyOption) (*models.AnalyticsProperty, error) { + path := "/analytics/properties" + options := CreatePropertyOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } + params := map[string]interface{}{} + params["propertyId"] = PropertyId + params["name"] = Name + if options.enabledSetters["Domain"] { + params["domain"] = options.Domain + } + if options.enabledSetters["Timezone"] { + params["timezone"] = options.Timezone + } + if options.enabledSetters["Enabled"] { + params["enabled"] = options.Enabled + } + if options.enabledSetters["Public"] { + params["public"] = options.Public + } + if options.enabledSetters["AllowedOrigins"] { + params["allowedOrigins"] = options.AllowedOrigins + } + headers := map[string]interface{}{} + headers["X-Appwrite-Project"] = srv.client.Config["project"] + headers["content-type"] = "application/json" + headers["accept"] = "application/json" + + resp, err := srv.client.Call("POST", path, headers, params) + if err != nil { + return nil, err + } + if strings.HasPrefix(resp.Type, "application/json") { + bytes, err := client.ResponseBody(resp) + if err != nil { + return nil, err + } + + parsed := models.AnalyticsProperty{}.New(bytes) + + err = json.Unmarshal(bytes, parsed) + if err != nil { + return nil, err + } + + return parsed, nil + } + var parsed models.AnalyticsProperty + parsed, ok := resp.Result.(models.AnalyticsProperty) + if !ok { + return nil, errors.New("unexpected response type") + } + return &parsed, nil + +} + +// GetProperty get an analytics property by ID. +func (srv *Analytics) GetProperty(PropertyId string) (*models.AnalyticsProperty, error) { + if PropertyId == "" { + return nil, errors.New("Missing required parameter: \"propertyId\"") + } + + r := strings.NewReplacer("{propertyId}", client.EncodePath(PropertyId)) + path := r.Replace("/analytics/properties/{propertyId}") + params := map[string]interface{}{} + headers := map[string]interface{}{} + headers["X-Appwrite-Project"] = srv.client.Config["project"] + headers["accept"] = "application/json" + + resp, err := srv.client.Call("GET", path, headers, params) + if err != nil { + return nil, err + } + if strings.HasPrefix(resp.Type, "application/json") { + bytes, err := client.ResponseBody(resp) + if err != nil { + return nil, err + } + + parsed := models.AnalyticsProperty{}.New(bytes) + + err = json.Unmarshal(bytes, parsed) + if err != nil { + return nil, err + } + + return parsed, nil + } + var parsed models.AnalyticsProperty + parsed, ok := resp.Result.(models.AnalyticsProperty) + if !ok { + return nil, errors.New("unexpected response type") + } + return &parsed, nil + +} + +type UpdatePropertyOptions struct { + Name string + Domain string + Timezone string + Enabled bool + Public bool + AllowedOrigins []string + enabledSetters map[string]bool +} + +func (options UpdatePropertyOptions) New() *UpdatePropertyOptions { + options.enabledSetters = map[string]bool{"Name": false, "Domain": false, "Timezone": false, "Enabled": false, "Public": false, "AllowedOrigins": false} + return &options +} + +type UpdatePropertyOption func(*UpdatePropertyOptions) + +func (srv *Analytics) WithUpdatePropertyName(v string) UpdatePropertyOption { + return func(o *UpdatePropertyOptions) { + o.Name = v + o.enabledSetters["Name"] = true + } +} +func (srv *Analytics) WithUpdatePropertyDomain(v string) UpdatePropertyOption { + return func(o *UpdatePropertyOptions) { + o.Domain = v + o.enabledSetters["Domain"] = true + } +} +func (srv *Analytics) WithUpdatePropertyTimezone(v string) UpdatePropertyOption { + return func(o *UpdatePropertyOptions) { + o.Timezone = v + o.enabledSetters["Timezone"] = true + } +} +func (srv *Analytics) WithUpdatePropertyEnabled(v bool) UpdatePropertyOption { + return func(o *UpdatePropertyOptions) { + o.Enabled = v + o.enabledSetters["Enabled"] = true + } +} +func (srv *Analytics) WithUpdatePropertyPublic(v bool) UpdatePropertyOption { + return func(o *UpdatePropertyOptions) { + o.Public = v + o.enabledSetters["Public"] = true + } +} +func (srv *Analytics) WithUpdatePropertyAllowedOrigins(v []string) UpdatePropertyOption { + return func(o *UpdatePropertyOptions) { + o.AllowedOrigins = v + o.enabledSetters["AllowedOrigins"] = true + } +} + +// UpdateProperty update an analytics property. Only the attributes you pass +// are changed; omitted attributes keep their current value. +func (srv *Analytics) UpdateProperty(PropertyId string, optionalSetters ...UpdatePropertyOption) (*models.AnalyticsProperty, error) { + if PropertyId == "" { + return nil, errors.New("Missing required parameter: \"propertyId\"") + } + + r := strings.NewReplacer("{propertyId}", client.EncodePath(PropertyId)) + path := r.Replace("/analytics/properties/{propertyId}") + options := UpdatePropertyOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } + params := map[string]interface{}{} + if options.enabledSetters["Name"] { + params["name"] = options.Name + } + if options.enabledSetters["Domain"] { + params["domain"] = options.Domain + } + if options.enabledSetters["Timezone"] { + params["timezone"] = options.Timezone + } + if options.enabledSetters["Enabled"] { + params["enabled"] = options.Enabled + } + if options.enabledSetters["Public"] { + params["public"] = options.Public + } + if options.enabledSetters["AllowedOrigins"] { + params["allowedOrigins"] = options.AllowedOrigins + } + headers := map[string]interface{}{} + headers["X-Appwrite-Project"] = srv.client.Config["project"] + headers["content-type"] = "application/json" + headers["accept"] = "application/json" + + resp, err := srv.client.Call("PATCH", path, headers, params) + if err != nil { + return nil, err + } + if strings.HasPrefix(resp.Type, "application/json") { + bytes, err := client.ResponseBody(resp) + if err != nil { + return nil, err + } + + parsed := models.AnalyticsProperty{}.New(bytes) + + err = json.Unmarshal(bytes, parsed) + if err != nil { + return nil, err + } + + return parsed, nil + } + var parsed models.AnalyticsProperty + parsed, ok := resp.Result.(models.AnalyticsProperty) + if !ok { + return nil, errors.New("unexpected response type") + } + return &parsed, nil + +} + +// DeleteProperty delete an analytics property along with every event and +// session collected for it. This cannot be undone. +func (srv *Analytics) DeleteProperty(PropertyId string) (*interface{}, error) { + if PropertyId == "" { + return nil, errors.New("Missing required parameter: \"propertyId\"") + } + + r := strings.NewReplacer("{propertyId}", client.EncodePath(PropertyId)) + path := r.Replace("/analytics/properties/{propertyId}") + params := map[string]interface{}{} + headers := map[string]interface{}{} + headers["X-Appwrite-Project"] = srv.client.Config["project"] + headers["content-type"] = "application/json" + headers["accept"] = "application/json" + + resp, err := srv.client.Call("DELETE", path, headers, params) + if err != nil { + return nil, err + } + if strings.HasPrefix(resp.Type, "application/json") { + bytes, err := client.ResponseBody(resp) + if err != nil { + return nil, err + } + + var parsed interface{} + + err = json.Unmarshal(bytes, &parsed) + if err != nil { + return nil, err + } + return &parsed, nil + } + var parsed interface{} + parsed, ok := resp.Result.(interface{}) + if !ok { + return nil, errors.New("unexpected response type") + } + return &parsed, nil + +} + +type CreateEventOptions struct { + Domain string + Referrer string + ScreenWidth int + SessionHash string + ScrollDepth int + EngagementTime int + Props []string + UserId string + Ip string + UserAgent string + enabledSetters map[string]bool +} + +func (options CreateEventOptions) New() *CreateEventOptions { + options.enabledSetters = map[string]bool{"Domain": false, "Referrer": false, "ScreenWidth": false, "SessionHash": false, "ScrollDepth": false, "EngagementTime": false, "Props": false, "UserId": false, "Ip": false, "UserAgent": false} + return &options +} + +type CreateEventOption func(*CreateEventOptions) + +func (srv *Analytics) WithCreateEventDomain(v string) CreateEventOption { + return func(o *CreateEventOptions) { + o.Domain = v + o.enabledSetters["Domain"] = true + } +} +func (srv *Analytics) WithCreateEventReferrer(v string) CreateEventOption { + return func(o *CreateEventOptions) { + o.Referrer = v + o.enabledSetters["Referrer"] = true + } +} +func (srv *Analytics) WithCreateEventScreenWidth(v int) CreateEventOption { + return func(o *CreateEventOptions) { + o.ScreenWidth = v + o.enabledSetters["ScreenWidth"] = true + } +} +func (srv *Analytics) WithCreateEventSessionHash(v string) CreateEventOption { + return func(o *CreateEventOptions) { + o.SessionHash = v + o.enabledSetters["SessionHash"] = true + } +} +func (srv *Analytics) WithCreateEventScrollDepth(v int) CreateEventOption { + return func(o *CreateEventOptions) { + o.ScrollDepth = v + o.enabledSetters["ScrollDepth"] = true + } +} +func (srv *Analytics) WithCreateEventEngagementTime(v int) CreateEventOption { + return func(o *CreateEventOptions) { + o.EngagementTime = v + o.enabledSetters["EngagementTime"] = true + } +} +func (srv *Analytics) WithCreateEventProps(v []string) CreateEventOption { + return func(o *CreateEventOptions) { + o.Props = v + o.enabledSetters["Props"] = true + } +} +func (srv *Analytics) WithCreateEventUserId(v string) CreateEventOption { + return func(o *CreateEventOptions) { + o.UserId = v + o.enabledSetters["UserId"] = true + } +} +func (srv *Analytics) WithCreateEventIp(v string) CreateEventOption { + return func(o *CreateEventOptions) { + o.Ip = v + o.enabledSetters["Ip"] = true + } +} +func (srv *Analytics) WithCreateEventUserAgent(v string) CreateEventOption { + return func(o *CreateEventOptions) { + o.UserAgent = v + o.enabledSetters["UserAgent"] = true + } +} + +// CreateEvent send a tracking event from a browser, native app, or +// server-side SDK. +func (srv *Analytics) CreateEvent(PropertyId string, Name string, Url string, optionalSetters ...CreateEventOption) (*interface{}, error) { + if PropertyId == "" { + return nil, errors.New("Missing required parameter: \"propertyId\"") + } + + r := strings.NewReplacer("{propertyId}", client.EncodePath(PropertyId)) + path := r.Replace("/analytics/properties/{propertyId}/events") + options := CreateEventOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } + params := map[string]interface{}{} + params["name"] = Name + params["url"] = Url + if options.enabledSetters["Domain"] { + params["domain"] = options.Domain + } + if options.enabledSetters["Referrer"] { + params["referrer"] = options.Referrer + } + if options.enabledSetters["ScreenWidth"] { + params["screenWidth"] = options.ScreenWidth + } + if options.enabledSetters["SessionHash"] { + params["sessionHash"] = options.SessionHash + } + if options.enabledSetters["ScrollDepth"] { + params["scrollDepth"] = options.ScrollDepth + } + if options.enabledSetters["EngagementTime"] { + params["engagementTime"] = options.EngagementTime + } + if options.enabledSetters["Props"] { + params["props"] = options.Props + } + if options.enabledSetters["UserId"] { + params["userId"] = options.UserId + } + if options.enabledSetters["Ip"] { + params["ip"] = options.Ip + } + if options.enabledSetters["UserAgent"] { + params["userAgent"] = options.UserAgent + } + headers := map[string]interface{}{} + headers["X-Appwrite-Project"] = srv.client.Config["project"] + headers["content-type"] = "application/json" + headers["accept"] = "application/json" + + resp, err := srv.client.Call("POST", path, headers, params) + if err != nil { + return nil, err + } + if strings.HasPrefix(resp.Type, "application/json") { + bytes, err := client.ResponseBody(resp) + if err != nil { + return nil, err + } + + var parsed interface{} + + err = json.Unmarshal(bytes, &parsed) + if err != nil { + return nil, err + } + return &parsed, nil + } + var parsed interface{} + parsed, ok := resp.Result.(interface{}) + if !ok { + return nil, errors.New("unexpected response type") + } + return &parsed, nil + +} + +type ListMetricsOptions struct { + Queries []string + Interval string + Dimensions []string + DateRange string + StartAt string + EndAt string + Limit int + enabledSetters map[string]bool +} + +func (options ListMetricsOptions) New() *ListMetricsOptions { + options.enabledSetters = map[string]bool{"Queries": false, "Interval": false, "Dimensions": false, "DateRange": false, "StartAt": false, "EndAt": false, "Limit": false} + return &options +} + +type ListMetricsOption func(*ListMetricsOptions) + +func (srv *Analytics) WithListMetricsQueries(v []string) ListMetricsOption { + return func(o *ListMetricsOptions) { + o.Queries = v + o.enabledSetters["Queries"] = true + } +} +func (srv *Analytics) WithListMetricsInterval(v string) ListMetricsOption { + return func(o *ListMetricsOptions) { + o.Interval = v + o.enabledSetters["Interval"] = true + } +} +func (srv *Analytics) WithListMetricsDimensions(v []string) ListMetricsOption { + return func(o *ListMetricsOptions) { + o.Dimensions = v + o.enabledSetters["Dimensions"] = true + } +} +func (srv *Analytics) WithListMetricsDateRange(v string) ListMetricsOption { + return func(o *ListMetricsOptions) { + o.DateRange = v + o.enabledSetters["DateRange"] = true + } +} +func (srv *Analytics) WithListMetricsStartAt(v string) ListMetricsOption { + return func(o *ListMetricsOptions) { + o.StartAt = v + o.enabledSetters["StartAt"] = true + } +} +func (srv *Analytics) WithListMetricsEndAt(v string) ListMetricsOption { + return func(o *ListMetricsOptions) { + o.EndAt = v + o.enabledSetters["EndAt"] = true + } +} +func (srv *Analytics) WithListMetricsLimit(v int) ListMetricsOption { + return func(o *ListMetricsOptions) { + o.Limit = v + o.enabledSetters["Limit"] = true + } +} + +// ListMetrics read analytics metrics (visitors, sessions, pageviews, events, +// bounceRate, …) for a property over a date range. +// +// **Three response shapes**, chosen by `dimensions[]` and `interval`: +// - Neither: one row aggregating the whole window, with `value` and `date` +// null. Only this shape carries `pageviews`, `visits`, `bounceRate`, +// `visitDuration`, `viewsPerVisit`, `scrollDepth` and `engagementTime`. +// - `dimensions[]`: one row per dimension value, ranked by visitors, with +// `value` set and `date` null. +// - `interval`: one row per time bucket in chronological order, with `date` +// set and `value` null. +// +// Combining `dimensions[]` with `interval` is not supported yet. `queries[]` +// filters the underlying events using standard Utopia query syntax. +func (srv *Analytics) ListMetrics(PropertyId string, optionalSetters ...ListMetricsOption) (*models.AnalyticsMetricList, error) { + if PropertyId == "" { + return nil, errors.New("Missing required parameter: \"propertyId\"") + } + + r := strings.NewReplacer("{propertyId}", client.EncodePath(PropertyId)) + path := r.Replace("/analytics/properties/{propertyId}/metrics") + options := ListMetricsOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } + params := map[string]interface{}{} + if options.enabledSetters["Queries"] { + params["queries"] = options.Queries + } + if options.enabledSetters["Interval"] { + params["interval"] = options.Interval + } + if options.enabledSetters["Dimensions"] { + params["dimensions"] = options.Dimensions + } + if options.enabledSetters["DateRange"] { + params["dateRange"] = options.DateRange + } + if options.enabledSetters["StartAt"] { + params["startAt"] = options.StartAt + } + if options.enabledSetters["EndAt"] { + params["endAt"] = options.EndAt + } + if options.enabledSetters["Limit"] { + params["limit"] = options.Limit + } + headers := map[string]interface{}{} + headers["X-Appwrite-Project"] = srv.client.Config["project"] + headers["accept"] = "application/json" + + resp, err := srv.client.Call("GET", path, headers, params) + if err != nil { + return nil, err + } + if strings.HasPrefix(resp.Type, "application/json") { + bytes, err := client.ResponseBody(resp) + if err != nil { + return nil, err + } + + parsed := models.AnalyticsMetricList{}.New(bytes) + + err = json.Unmarshal(bytes, parsed) + if err != nil { + return nil, err + } + + return parsed, nil + } + var parsed models.AnalyticsMetricList + parsed, ok := resp.Result.(models.AnalyticsMetricList) + if !ok { + return nil, errors.New("unexpected response type") + } + return &parsed, nil + +} diff --git a/analytics/analytics_test.go b/analytics/analytics_test.go new file mode 100644 index 00000000..03bba09e --- /dev/null +++ b/analytics/analytics_test.go @@ -0,0 +1,248 @@ +package analytics + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/appwrite/sdk-for-go/v7/client" +) + +func TestAnalytics(t *testing.T) { + newTestClient := func(ts *httptest.Server) client.Client { + c := client.New() + c.Endpoint = ts.URL + c.Client = ts.Client() + return c + } + + t.Run("Test ListProperties", func(t *testing.T) { + mockResponse := ` +{ + "total": 5, + "properties": [ + { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "My Website", + "domain": "example.com", + "timezone": "UTC", + "enabled": true, + "public": true, + "allowedOrigins": [], + "snippetId": "snp_a1b2c3d4e5" + } + ] +} +` + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + t.Errorf("Expected method GET, got %s", r.Method) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(mockResponse)) + })) + defer ts.Close() + + srv := New(newTestClient(ts)) + + _, err := srv.ListProperties() + if err != nil { + t.Errorf("Method ListProperties failed: %v", err) + } + }) + + t.Run("Test CreateProperty", func(t *testing.T) { + mockResponse := ` +{ + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "My Website", + "domain": "example.com", + "timezone": "UTC", + "enabled": true, + "public": true, + "allowedOrigins": [], + "snippetId": "snp_a1b2c3d4e5" +} +` + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + t.Errorf("Expected method POST, got %s", r.Method) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(mockResponse)) + })) + defer ts.Close() + + srv := New(newTestClient(ts)) + + _, err := srv.CreateProperty("", "") + if err != nil { + t.Errorf("Method CreateProperty failed: %v", err) + } + }) + + t.Run("Test GetProperty", func(t *testing.T) { + mockResponse := ` +{ + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "My Website", + "domain": "example.com", + "timezone": "UTC", + "enabled": true, + "public": true, + "allowedOrigins": [], + "snippetId": "snp_a1b2c3d4e5" +} +` + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + t.Errorf("Expected method GET, got %s", r.Method) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(mockResponse)) + })) + defer ts.Close() + + srv := New(newTestClient(ts)) + + _, err := srv.GetProperty("") + if err != nil { + t.Errorf("Method GetProperty failed: %v", err) + } + }) + + t.Run("Test UpdateProperty", func(t *testing.T) { + mockResponse := ` +{ + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "My Website", + "domain": "example.com", + "timezone": "UTC", + "enabled": true, + "public": true, + "allowedOrigins": [], + "snippetId": "snp_a1b2c3d4e5" +} +` + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "PATCH" { + t.Errorf("Expected method PATCH, got %s", r.Method) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(mockResponse)) + })) + defer ts.Close() + + srv := New(newTestClient(ts)) + + _, err := srv.UpdateProperty("") + if err != nil { + t.Errorf("Method UpdateProperty failed: %v", err) + } + }) + + t.Run("Test DeleteProperty", func(t *testing.T) { + mockResponse := ` +{ + "message": "success" +} +` + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "DELETE" { + t.Errorf("Expected method DELETE, got %s", r.Method) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(mockResponse)) + })) + defer ts.Close() + + srv := New(newTestClient(ts)) + + _, err := srv.DeleteProperty("") + if err != nil { + t.Errorf("Method DeleteProperty failed: %v", err) + } + }) + + t.Run("Test CreateEvent", func(t *testing.T) { + mockResponse := ` +{ + "message": "success" +} +` + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + t.Errorf("Expected method POST, got %s", r.Method) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(mockResponse)) + })) + defer ts.Close() + + srv := New(newTestClient(ts)) + + _, err := srv.CreateEvent("", "", "https://example.com") + if err != nil { + t.Errorf("Method CreateEvent failed: %v", err) + } + }) + + t.Run("Test ListMetrics", func(t *testing.T) { + mockResponse := ` +{ + "total": 30, + "metrics": [ + { + "visitors": 1234, + "sessions": 4567, + "events": 8910 + } + ] +} +` + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + t.Errorf("Expected method GET, got %s", r.Method) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(mockResponse)) + })) + defer ts.Close() + + srv := New(newTestClient(ts)) + + _, err := srv.ListMetrics("") + if err != nil { + t.Errorf("Method ListMetrics failed: %v", err) + } + }) +} diff --git a/appwrite/appwrite.go b/appwrite/appwrite.go index a0b0562f..1d285cce 100644 --- a/appwrite/appwrite.go +++ b/appwrite/appwrite.go @@ -8,6 +8,7 @@ import ( "github.com/appwrite/sdk-for-go/v7/account" "github.com/appwrite/sdk-for-go/v7/activities" "github.com/appwrite/sdk-for-go/v7/advisor" + "github.com/appwrite/sdk-for-go/v7/analytics" "github.com/appwrite/sdk-for-go/v7/apps" "github.com/appwrite/sdk-for-go/v7/avatars" "github.com/appwrite/sdk-for-go/v7/backups" @@ -43,6 +44,9 @@ func NewAccount(clt client.Client) *account.Account { func NewActivities(clt client.Client) *activities.Activities { return activities.New(clt) } +func NewAnalytics(clt client.Client) *analytics.Analytics { + return analytics.New(clt) +} func NewApps(clt client.Client) *apps.Apps { return apps.New(clt) } diff --git a/avatars/avatars.go b/avatars/avatars.go index 1785c5ff..39038c22 100644 --- a/avatars/avatars.go +++ b/avatars/avatars.go @@ -7,6 +7,8 @@ import ( "strings" "github.com/appwrite/sdk-for-go/v7/client" + "github.com/appwrite/sdk-for-go/v7/file" + "github.com/appwrite/sdk-for-go/v7/models" ) // Avatars service @@ -815,8 +817,8 @@ func (srv *Avatars) getPhotoParams(optionalSetters ...GetPhotoOption) map[string // GetPhoto returns the best available profile photo for a user. The endpoint // tries each source in priority order and returns the first successful -// result: OAuth2 identity photo, Gravatar, Libravatar, Appwrite Initials, -// built-in static fallback. +// result: a custom uploaded photo (see avatars.updatePhoto), OAuth2 identity +// photo, Gravatar, Libravatar, Appwrite Initials, built-in static fallback. // // Passing `userId` — `current()` for the authenticated user — resolves // the photo from everything known about that user: identity photos, email, @@ -864,8 +866,9 @@ func (srv *Avatars) GetPhoto(optionalSetters ...GetPhotoOption) (*[]byte, error) // GetPhotoURL returns the best available profile photo for a user. The // endpoint tries each source in priority order and returns the first -// successful result: OAuth2 identity photo, Gravatar, Libravatar, Appwrite -// Initials, built-in static fallback. +// successful result: a custom uploaded photo (see avatars.updatePhoto), +// OAuth2 identity photo, Gravatar, Libravatar, Appwrite Initials, built-in +// static fallback. // // Passing `userId` — `current()` for the authenticated user — resolves // the photo from everything known about that user: identity photos, email, @@ -894,6 +897,88 @@ func (srv *Avatars) GetPhotoURL(optionalSetters ...GetPhotoOption) (*string, err return &result, nil } +// UpdatePhoto update the profile photo of the currently authenticated user. +// The uploaded image takes priority over every other photo source, including +// OAuth2 identity photos, Gravatar, and Libravatar. Updating an already +// customized photo replaces it. The image must be at most 5MB and is sent in +// a single request. +func (srv *Avatars) UpdatePhoto(File file.InputFile) (*models.Account, error) { + path := "/avatars/photo" + params := map[string]interface{}{} + params["file"] = File + headers := map[string]interface{}{} + headers["X-Appwrite-Project"] = srv.client.Config["project"] + headers["content-type"] = "multipart/form-data" + headers["accept"] = "application/json" + + paramName := "file" + + uploadId := "" + + resp, err := srv.client.FileUpload(path, headers, params, paramName, uploadId, "PUT") + if err != nil { + return nil, err + } + if strings.HasPrefix(resp.Type, "application/json") { + bytes, err := client.ResponseBody(resp) + if err != nil { + return nil, err + } + parsed := models.Account{}.New(bytes) + if err := json.Unmarshal(bytes, parsed); err != nil { + return nil, err + } + return parsed, nil + } + var parsed models.Account + parsed, ok := resp.Result.(models.Account) + if !ok { + return nil, errors.New("unexpected response type") + } + return &parsed, nil + +} + +// DeletePhoto delete the profile photo of the currently authenticated user +// and store the built-in static placeholder in its place. The placeholder is +// the user's photo from then on, so it takes priority over every other photo +// source — OAuth2 identity photos, Gravatar, Libravatar, and initials — +// until a new photo is uploaded with avatars.updatePhoto. +func (srv *Avatars) DeletePhoto() (*interface{}, error) { + path := "/avatars/photo" + params := map[string]interface{}{} + headers := map[string]interface{}{} + headers["X-Appwrite-Project"] = srv.client.Config["project"] + headers["content-type"] = "application/json" + headers["accept"] = "application/json" + + resp, err := srv.client.Call("DELETE", path, headers, params) + if err != nil { + return nil, err + } + if strings.HasPrefix(resp.Type, "application/json") { + bytes, err := client.ResponseBody(resp) + if err != nil { + return nil, err + } + + var parsed interface{} + + err = json.Unmarshal(bytes, &parsed) + if err != nil { + return nil, err + } + return &parsed, nil + } + var parsed interface{} + parsed, ok := resp.Result.(interface{}) + if !ok { + return nil, errors.New("unexpected response type") + } + return &parsed, nil + +} + type GetQROptions struct { Size int Margin int diff --git a/avatars/avatars_test.go b/avatars/avatars_test.go index 9aedac68..3a78b1bd 100644 --- a/avatars/avatars_test.go +++ b/avatars/avatars_test.go @@ -3,12 +3,21 @@ package avatars import ( "net/http" "net/http/httptest" + "os" "testing" "github.com/appwrite/sdk-for-go/v7/client" + "github.com/appwrite/sdk-for-go/v7/file" ) func TestAvatars(t *testing.T) { + tmpFile, err := os.CreateTemp("", "test") + if err != nil { + t.Fatal(err) + } + defer os.Remove(tmpFile.Name()) + _, _ = tmpFile.WriteString("test content") + _ = tmpFile.Close() newTestClient := func(ts *httptest.Server) client.Client { c := client.New() c.Endpoint = ts.URL @@ -170,6 +179,92 @@ func TestAvatars(t *testing.T) { } }) + t.Run("Test UpdatePhoto", func(t *testing.T) { + mockResponse := ` +{ + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "John Doe", + "registration": "2020-10-15T06:38:00.000+00:00", + "status": true, + "labels": [], + "passwordUpdate": "2020-10-15T06:38:00.000+00:00", + "email": "john@appwrite.io", + "phone": "+4930901820", + "emailVerification": true, + "phoneVerification": true, + "mfa": true, + "prefs": { + }, + "targets": [ + { + "$id": "259125845563242502", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Apple iPhone 12", + "userId": "259125845563242502", + "providerType": "email", + "identifier": "token", + "expired": true + } + ], + "accessedAt": "2020-10-15T06:38:00.000+00:00" +} +` + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == "GET" && "PUT" != "GET" { + // Handle file upload resume check + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"chunksUploaded": 0}`)) + return + } + if r.Method != "PUT" { + t.Errorf("Expected method PUT, got %s", r.Method) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(mockResponse)) + })) + defer ts.Close() + + srv := New(newTestClient(ts)) + + _, err := srv.UpdatePhoto(file.NewInputFile(tmpFile.Name(), "test.txt")) + if err != nil { + t.Errorf("Method UpdatePhoto failed: %v", err) + } + }) + + t.Run("Test DeletePhoto", func(t *testing.T) { + mockResponse := ` +{ + "message": "success" +} +` + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "DELETE" { + t.Errorf("Expected method DELETE, got %s", r.Method) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(mockResponse)) + })) + defer ts.Close() + + srv := New(newTestClient(ts)) + + _, err := srv.DeletePhoto() + if err != nil { + t.Errorf("Method DeletePhoto failed: %v", err) + } + }) + t.Run("Test GetQR", func(t *testing.T) { mockData := []byte("image_data") diff --git a/backups/backups_test.go b/backups/backups_test.go index 12b29777..3320a926 100644 --- a/backups/backups_test.go +++ b/backups/backups_test.go @@ -26,9 +26,7 @@ func TestBackups(t *testing.T) { "$createdAt": "2020-10-15T06:38:00.000+00:00", "$updatedAt": "2020-10-15T06:38:00.000+00:00", "policyId": "did8jx6ws45jana098ab7", - "size": 100000, "status": "completed", - "startedAt": "2020-10-15T06:38:00.000+00:00", "migrationId": "did8jx6ws45jana098ab7", "services": [], "resources": [] @@ -63,9 +61,7 @@ func TestBackups(t *testing.T) { "$createdAt": "2020-10-15T06:38:00.000+00:00", "$updatedAt": "2020-10-15T06:38:00.000+00:00", "policyId": "did8jx6ws45jana098ab7", - "size": 100000, "status": "completed", - "startedAt": "2020-10-15T06:38:00.000+00:00", "migrationId": "did8jx6ws45jana098ab7", "services": [], "resources": [] @@ -98,9 +94,7 @@ func TestBackups(t *testing.T) { "$createdAt": "2020-10-15T06:38:00.000+00:00", "$updatedAt": "2020-10-15T06:38:00.000+00:00", "policyId": "did8jx6ws45jana098ab7", - "size": 100000, "status": "completed", - "startedAt": "2020-10-15T06:38:00.000+00:00", "migrationId": "did8jx6ws45jana098ab7", "services": [], "resources": [] @@ -221,7 +215,7 @@ func TestBackups(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.CreatePolicy("", []string{}, 1, "") + _, err := srv.CreatePolicy("", []string{}, 1, "schedule") if err != nil { t.Errorf("Method CreatePolicy failed: %v", err) } @@ -332,11 +326,10 @@ func TestBackups(t *testing.T) { "archiveId": "did8jx6ws45jana098ab7", "policyId": "did8jx6ws45jana098ab7", "status": "completed", - "startedAt": "2020-10-15T06:38:00.000+00:00", "migrationId": "did8jx6ws45jana098ab7", "services": [], "resources": [], - "options": "{databases.database[{oldId, newId, newName}]}" + "options": {} } ` @@ -371,11 +364,10 @@ func TestBackups(t *testing.T) { "archiveId": "did8jx6ws45jana098ab7", "policyId": "did8jx6ws45jana098ab7", "status": "completed", - "startedAt": "2020-10-15T06:38:00.000+00:00", "migrationId": "did8jx6ws45jana098ab7", "services": [], "resources": [], - "options": "{databases.database[{oldId, newId, newName}]}" + "options": {} } ] } @@ -409,11 +401,10 @@ func TestBackups(t *testing.T) { "archiveId": "did8jx6ws45jana098ab7", "policyId": "did8jx6ws45jana098ab7", "status": "completed", - "startedAt": "2020-10-15T06:38:00.000+00:00", "migrationId": "did8jx6ws45jana098ab7", "services": [], "resources": [], - "options": "{databases.database[{oldId, newId, newName}]}" + "options": {} } ` diff --git a/client/client.go b/client/client.go index 74130d09..ff49f8e7 100644 --- a/client/client.go +++ b/client/client.go @@ -80,11 +80,11 @@ type Client struct { func New(optionalSetters ...ClientOption) Client { headers := map[string]string{} headers["X-Appwrite-Response-Format"] = "2.3.0" - headers["user-agent"] = fmt.Sprintf("AppwriteGoSDK/v7.5.0 (%s; %s)", runtime.GOOS, runtime.GOARCH) + headers["user-agent"] = fmt.Sprintf("AppwriteGoSDK/v7.6.0 (%s; %s)", runtime.GOOS, runtime.GOARCH) headers["x-sdk-name"] = "Go" headers["x-sdk-platform"] = "server" headers["x-sdk-language"] = "go" - headers["x-sdk-version"] = "v7.5.0" + headers["x-sdk-version"] = "v7.6.0" httpClient, err := GetDefaultClient(defaultTimeout) if err != nil { panic(err) @@ -213,8 +213,52 @@ func copyParams(params map[string]interface{}) map[string]interface{} { return clone } -func (client *Client) FileUpload(url string, headers map[string]interface{}, params map[string]interface{}, paramName string, uploadId string) (*ClientResponse, error) { +// uploadMethod returns the HTTP method an upload helper sends with. The +// method is optional so callers written before it existed keep sending POST. +func uploadMethod(method []string) string { + if len(method) > 0 && method[0] != "" { + return method[0] + } + return "POST" +} + +// SingleUpload sends the file in one request. method is the endpoint's HTTP +// method and defaults to POST. +func (client *Client) SingleUpload(url string, headers map[string]interface{}, params map[string]interface{}, paramName string, method ...string) (*ClientResponse, error) { + httpMethod := uploadMethod(method) inputFile, ok := params[paramName].(file.InputFile) + if _, present := params[paramName]; !present { + return client.Call(httpMethod, url, headers, params) + } + if !ok { + msg := fmt.Sprintf("invalid input file. params[%s] must be of type file.InputFile", paramName) + return nil, errors.New(msg) + } + + source, err := os.Open(inputFile.Path) + if err != nil { + return nil, err + } + defer source.Close() + + var content bytes.Buffer + if _, err := content.ReadFrom(source); err != nil { + return nil, err + } + inputFile.Data = content.Bytes() + params[paramName] = inputFile + + return client.Call(httpMethod, url, headers, params) +} + +// FileUpload sends the file in chunks, resuming uploadId when it is set. +// method is the endpoint's HTTP method and defaults to POST. +func (client *Client) FileUpload(url string, headers map[string]interface{}, params map[string]interface{}, paramName string, uploadId string, method ...string) (*ClientResponse, error) { + httpMethod := uploadMethod(method) + inputFile, ok := params[paramName].(file.InputFile) + if _, present := params[paramName]; !present { + return client.Call(httpMethod, url, headers, params) + } if !ok { msg := fmt.Sprintf("invalid input file. params[%s] must be of type file.InputFile", paramName) return nil, errors.New(msg) @@ -265,7 +309,7 @@ func (client *Client) FileUpload(url string, headers map[string]interface{}, par } params[paramName] = inputFile - result, err = client.Call("POST", url, headers, params) + result, err = client.Call(httpMethod, url, headers, params) if err != nil { return nil, err } @@ -349,7 +393,7 @@ func (client *Client) FileUpload(url string, headers map[string]interface{}, par end := offset + chunkSize - 1 chunkHeaders["content-range"] = fmt.Sprintf("bytes %d-%d/%d", start, end, totalSize) - return client.Call("POST", url, chunkHeaders, chunkParams) + return client.Call(httpMethod, url, chunkHeaders, chunkParams) } if currentChunk == 0 { @@ -453,15 +497,14 @@ func (client *Client) Call(method string, path string, headers map[string]interf urlPath := client.Endpoint + path isGet := strings.ToUpper(method) == "GET" - isPost := strings.ToUpper(method) == "POST" isJsonRequest := headers["content-type"] == "application/json" isFileUpload := isFileUpload(headers) var req *http.Request var err error if isFileUpload { - if !isPost { - return nil, errors.New("fileupload needs POST Request") + if isGet { + return nil, errors.New("fileupload cannot be sent as a GET request") } var body bytes.Buffer writer := multipart.NewWriter(&body) diff --git a/databases/databases.go b/databases/databases.go index b1473ef1..86a4c950 100644 --- a/databases/databases.go +++ b/databases/databases.go @@ -175,11 +175,12 @@ func (srv *Databases) Create(DatabaseId string, Name string, optionalSetters ... type ListTransactionsOptions struct { Queries []string + Total bool enabledSetters map[string]bool } func (options ListTransactionsOptions) New() *ListTransactionsOptions { - options.enabledSetters = map[string]bool{"Queries": false} + options.enabledSetters = map[string]bool{"Queries": false, "Total": false} return &options } @@ -191,6 +192,12 @@ func (srv *Databases) WithListTransactionsQueries(v []string) ListTransactionsOp o.enabledSetters["Queries"] = true } } +func (srv *Databases) WithListTransactionsTotal(v bool) ListTransactionsOption { + return func(o *ListTransactionsOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} // ListTransactions list transactions across all databases. // @@ -205,6 +212,9 @@ func (srv *Databases) ListTransactions(optionalSetters ...ListTransactionsOption if options.enabledSetters["Queries"] { params["queries"] = options.Queries } + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" diff --git a/docs/examples/account/create-email-password-session.md b/docs/examples/account/create-email-password-session.md index 0fc7cb4b..f922baf2 100644 --- a/docs/examples/account/create-email-password-session.md +++ b/docs/examples/account/create-email-password-session.md @@ -20,6 +20,7 @@ func main() { response, err := service.CreateEmailPasswordSession( "email@example.com", "password", + service.WithCreateEmailPasswordSessionDuration(60), ) fmt.Println(response, err) } diff --git a/docs/examples/account/delete-sessions.md b/docs/examples/account/delete-sessions.md index 2cae6cb0..5f741a69 100644 --- a/docs/examples/account/delete-sessions.md +++ b/docs/examples/account/delete-sessions.md @@ -17,7 +17,9 @@ func main() { service := account.New(client) - response, err := service.DeleteSessions() + response, err := service.DeleteSessions( + service.WithDeleteSessionsCurrent(false), + ) fmt.Println(response, err) } ``` diff --git a/docs/examples/account/list-sessions.md b/docs/examples/account/list-sessions.md index 6d4315e1..44429f0b 100644 --- a/docs/examples/account/list-sessions.md +++ b/docs/examples/account/list-sessions.md @@ -17,7 +17,9 @@ func main() { service := account.New(client) - response, err := service.ListSessions() + response, err := service.ListSessions( + service.WithListSessionsTotal(false), + ) fmt.Println(response, err) } ``` diff --git a/docs/examples/analytics/create-event.md b/docs/examples/analytics/create-event.md new file mode 100644 index 00000000..7cf153d1 --- /dev/null +++ b/docs/examples/analytics/create-event.md @@ -0,0 +1,37 @@ +```go +package main + +import ( + "fmt" + + "github.com/appwrite/sdk-for-go/v7/analytics" + "github.com/appwrite/sdk-for-go/v7/appwrite" +) + +func main() { + client := appwrite.NewClient( + appwrite.WithEndpoint("https://.cloud.appwrite.io/v1"), + appwrite.WithProject(""), + appwrite.WithSession(""), + ) + + service := analytics.New(client) + + response, err := service.CreateEvent( + "", + "", + "https://example.com", + service.WithCreateEventDomain(""), + service.WithCreateEventReferrer(""), + service.WithCreateEventScreenWidth(0), + service.WithCreateEventSessionHash(""), + service.WithCreateEventScrollDepth(0), + service.WithCreateEventEngagementTime(0), + service.WithCreateEventProps([]string{"example"}), + service.WithCreateEventUserId(""), + service.WithCreateEventIp(""), + service.WithCreateEventUserAgent(""), + ) + fmt.Println(response, err) +} +``` diff --git a/docs/examples/analytics/create-property.md b/docs/examples/analytics/create-property.md new file mode 100644 index 00000000..6b4c356e --- /dev/null +++ b/docs/examples/analytics/create-property.md @@ -0,0 +1,31 @@ +```go +package main + +import ( + "fmt" + + "github.com/appwrite/sdk-for-go/v7/analytics" + "github.com/appwrite/sdk-for-go/v7/appwrite" +) + +func main() { + client := appwrite.NewClient( + appwrite.WithEndpoint("https://.cloud.appwrite.io/v1"), + appwrite.WithProject(""), + appwrite.WithKey(""), + ) + + service := analytics.New(client) + + response, err := service.CreateProperty( + "", + "", + service.WithCreatePropertyDomain(""), + service.WithCreatePropertyTimezone(""), + service.WithCreatePropertyEnabled(false), + service.WithCreatePropertyPublic(false), + service.WithCreatePropertyAllowedOrigins([]string{"example"}), + ) + fmt.Println(response, err) +} +``` diff --git a/docs/examples/analytics/delete-property.md b/docs/examples/analytics/delete-property.md new file mode 100644 index 00000000..f1153f55 --- /dev/null +++ b/docs/examples/analytics/delete-property.md @@ -0,0 +1,25 @@ +```go +package main + +import ( + "fmt" + + "github.com/appwrite/sdk-for-go/v7/analytics" + "github.com/appwrite/sdk-for-go/v7/appwrite" +) + +func main() { + client := appwrite.NewClient( + appwrite.WithEndpoint("https://.cloud.appwrite.io/v1"), + appwrite.WithProject(""), + appwrite.WithKey(""), + ) + + service := analytics.New(client) + + response, err := service.DeleteProperty( + "", + ) + fmt.Println(response, err) +} +``` diff --git a/docs/examples/analytics/get-property.md b/docs/examples/analytics/get-property.md new file mode 100644 index 00000000..446b26cd --- /dev/null +++ b/docs/examples/analytics/get-property.md @@ -0,0 +1,25 @@ +```go +package main + +import ( + "fmt" + + "github.com/appwrite/sdk-for-go/v7/analytics" + "github.com/appwrite/sdk-for-go/v7/appwrite" +) + +func main() { + client := appwrite.NewClient( + appwrite.WithEndpoint("https://.cloud.appwrite.io/v1"), + appwrite.WithProject(""), + appwrite.WithKey(""), + ) + + service := analytics.New(client) + + response, err := service.GetProperty( + "", + ) + fmt.Println(response, err) +} +``` diff --git a/docs/examples/analytics/list-metrics.md b/docs/examples/analytics/list-metrics.md new file mode 100644 index 00000000..ccfe492e --- /dev/null +++ b/docs/examples/analytics/list-metrics.md @@ -0,0 +1,32 @@ +```go +package main + +import ( + "fmt" + + "github.com/appwrite/sdk-for-go/v7/analytics" + "github.com/appwrite/sdk-for-go/v7/appwrite" +) + +func main() { + client := appwrite.NewClient( + appwrite.WithEndpoint("https://.cloud.appwrite.io/v1"), + appwrite.WithProject(""), + appwrite.WithKey(""), + ) + + service := analytics.New(client) + + response, err := service.ListMetrics( + "", + service.WithListMetricsQueries([]string{"example"}), + service.WithListMetricsInterval("1h"), + service.WithListMetricsDimensions([]string{"example"}), + service.WithListMetricsDateRange(""), + service.WithListMetricsStartAt("2020-10-15T06:38:00.000+00:00"), + service.WithListMetricsEndAt("2020-10-15T06:38:00.000+00:00"), + service.WithListMetricsLimit(1), + ) + fmt.Println(response, err) +} +``` diff --git a/docs/examples/analytics/list-properties.md b/docs/examples/analytics/list-properties.md new file mode 100644 index 00000000..21141f68 --- /dev/null +++ b/docs/examples/analytics/list-properties.md @@ -0,0 +1,27 @@ +```go +package main + +import ( + "fmt" + + "github.com/appwrite/sdk-for-go/v7/analytics" + "github.com/appwrite/sdk-for-go/v7/appwrite" +) + +func main() { + client := appwrite.NewClient( + appwrite.WithEndpoint("https://.cloud.appwrite.io/v1"), + appwrite.WithProject(""), + appwrite.WithKey(""), + ) + + service := analytics.New(client) + + response, err := service.ListProperties( + service.WithListPropertiesQueries([]string{"example"}), + service.WithListPropertiesSearch(""), + service.WithListPropertiesTotal(false), + ) + fmt.Println(response, err) +} +``` diff --git a/docs/examples/analytics/update-property.md b/docs/examples/analytics/update-property.md new file mode 100644 index 00000000..f29df588 --- /dev/null +++ b/docs/examples/analytics/update-property.md @@ -0,0 +1,31 @@ +```go +package main + +import ( + "fmt" + + "github.com/appwrite/sdk-for-go/v7/analytics" + "github.com/appwrite/sdk-for-go/v7/appwrite" +) + +func main() { + client := appwrite.NewClient( + appwrite.WithEndpoint("https://.cloud.appwrite.io/v1"), + appwrite.WithProject(""), + appwrite.WithKey(""), + ) + + service := analytics.New(client) + + response, err := service.UpdateProperty( + "", + service.WithUpdatePropertyName(""), + service.WithUpdatePropertyDomain(""), + service.WithUpdatePropertyTimezone(""), + service.WithUpdatePropertyEnabled(false), + service.WithUpdatePropertyPublic(false), + service.WithUpdatePropertyAllowedOrigins([]string{"example"}), + ) + fmt.Println(response, err) +} +``` diff --git a/docs/examples/avatars/delete-photo.md b/docs/examples/avatars/delete-photo.md new file mode 100644 index 00000000..c3fb60b9 --- /dev/null +++ b/docs/examples/avatars/delete-photo.md @@ -0,0 +1,23 @@ +```go +package main + +import ( + "fmt" + + "github.com/appwrite/sdk-for-go/v7/appwrite" + "github.com/appwrite/sdk-for-go/v7/avatars" +) + +func main() { + client := appwrite.NewClient( + appwrite.WithEndpoint("https://.cloud.appwrite.io/v1"), + appwrite.WithProject(""), + appwrite.WithSession(""), + ) + + service := avatars.New(client) + + response, err := service.DeletePhoto() + fmt.Println(response, err) +} +``` diff --git a/docs/examples/avatars/get-screenshot.md b/docs/examples/avatars/get-screenshot.md index 2fa9098f..1f699b7f 100644 --- a/docs/examples/avatars/get-screenshot.md +++ b/docs/examples/avatars/get-screenshot.md @@ -19,7 +19,7 @@ func main() { response, err := service.GetScreenshot( "https://example.com", - service.WithGetScreenshotHeaders(map[string]interface{}{"Authorization": "Bearer token123", "X-Custom-Header": "value"}), + service.WithGetScreenshotHeaders(map[string]interface{}{"Accept-Language": "en-US,en;q=0.9"}), service.WithGetScreenshotViewportWidth(1920), service.WithGetScreenshotViewportHeight(1080), service.WithGetScreenshotScale(2), diff --git a/docs/examples/avatars/update-photo.md b/docs/examples/avatars/update-photo.md new file mode 100644 index 00000000..36c161e8 --- /dev/null +++ b/docs/examples/avatars/update-photo.md @@ -0,0 +1,26 @@ +```go +package main + +import ( + "fmt" + + "github.com/appwrite/sdk-for-go/v7/appwrite" + "github.com/appwrite/sdk-for-go/v7/avatars" + "github.com/appwrite/sdk-for-go/v7/file" +) + +func main() { + client := appwrite.NewClient( + appwrite.WithEndpoint("https://.cloud.appwrite.io/v1"), + appwrite.WithProject(""), + appwrite.WithSession(""), + ) + + service := avatars.New(client) + + response, err := service.UpdatePhoto( + file.NewInputFile("/path/to/file.png", "file.png"), + ) + fmt.Println(response, err) +} +``` diff --git a/docs/examples/databases/list-transactions.md b/docs/examples/databases/list-transactions.md index 1c991e74..f006b5a1 100644 --- a/docs/examples/databases/list-transactions.md +++ b/docs/examples/databases/list-transactions.md @@ -19,6 +19,7 @@ func main() { response, err := service.ListTransactions( service.WithListTransactionsQueries([]string{"example"}), + service.WithListTransactionsTotal(false), ) fmt.Println(response, err) } diff --git a/docs/examples/documentsdb/list-transactions.md b/docs/examples/documentsdb/list-transactions.md index e2d8553f..89efe551 100644 --- a/docs/examples/documentsdb/list-transactions.md +++ b/docs/examples/documentsdb/list-transactions.md @@ -19,6 +19,7 @@ func main() { response, err := service.ListTransactions( service.WithListTransactionsQueries([]string{"example"}), + service.WithListTransactionsTotal(false), ) fmt.Println(response, err) } diff --git a/docs/examples/functions/list-runtimes.md b/docs/examples/functions/list-runtimes.md index 86c2ecfe..ae03a1af 100644 --- a/docs/examples/functions/list-runtimes.md +++ b/docs/examples/functions/list-runtimes.md @@ -17,7 +17,9 @@ func main() { service := functions.New(client) - response, err := service.ListRuntimes() + response, err := service.ListRuntimes( + service.WithListRuntimesTotal(false), + ) fmt.Println(response, err) } ``` diff --git a/docs/examples/functions/list-specifications.md b/docs/examples/functions/list-specifications.md index e96ac131..59438f97 100644 --- a/docs/examples/functions/list-specifications.md +++ b/docs/examples/functions/list-specifications.md @@ -19,6 +19,7 @@ func main() { response, err := service.ListSpecifications( service.WithListSpecificationsType("runtimes"), + service.WithListSpecificationsTotal(false), ) fmt.Println(response, err) } diff --git a/docs/examples/locale/list-codes.md b/docs/examples/locale/list-codes.md index 392e9ad7..ade207f8 100644 --- a/docs/examples/locale/list-codes.md +++ b/docs/examples/locale/list-codes.md @@ -17,7 +17,9 @@ func main() { service := locale.New(client) - response, err := service.ListCodes() + response, err := service.ListCodes( + service.WithListCodesTotal(false), + ) fmt.Println(response, err) } ``` diff --git a/docs/examples/locale/list-continents.md b/docs/examples/locale/list-continents.md index 137084c5..643734b9 100644 --- a/docs/examples/locale/list-continents.md +++ b/docs/examples/locale/list-continents.md @@ -17,7 +17,9 @@ func main() { service := locale.New(client) - response, err := service.ListContinents() + response, err := service.ListContinents( + service.WithListContinentsTotal(false), + ) fmt.Println(response, err) } ``` diff --git a/docs/examples/locale/list-countries-eu.md b/docs/examples/locale/list-countries-eu.md index bfa6d66f..cc88ed19 100644 --- a/docs/examples/locale/list-countries-eu.md +++ b/docs/examples/locale/list-countries-eu.md @@ -17,7 +17,9 @@ func main() { service := locale.New(client) - response, err := service.ListCountriesEU() + response, err := service.ListCountriesEU( + service.WithListCountriesEUTotal(false), + ) fmt.Println(response, err) } ``` diff --git a/docs/examples/locale/list-countries-phones.md b/docs/examples/locale/list-countries-phones.md index f4732a1c..682a9171 100644 --- a/docs/examples/locale/list-countries-phones.md +++ b/docs/examples/locale/list-countries-phones.md @@ -17,7 +17,9 @@ func main() { service := locale.New(client) - response, err := service.ListCountriesPhones() + response, err := service.ListCountriesPhones( + service.WithListCountriesPhonesTotal(false), + ) fmt.Println(response, err) } ``` diff --git a/docs/examples/locale/list-countries.md b/docs/examples/locale/list-countries.md index 85e9f3e8..bd7b5e19 100644 --- a/docs/examples/locale/list-countries.md +++ b/docs/examples/locale/list-countries.md @@ -17,7 +17,9 @@ func main() { service := locale.New(client) - response, err := service.ListCountries() + response, err := service.ListCountries( + service.WithListCountriesTotal(false), + ) fmt.Println(response, err) } ``` diff --git a/docs/examples/locale/list-currencies.md b/docs/examples/locale/list-currencies.md index 6ab6d25d..94016731 100644 --- a/docs/examples/locale/list-currencies.md +++ b/docs/examples/locale/list-currencies.md @@ -17,7 +17,9 @@ func main() { service := locale.New(client) - response, err := service.ListCurrencies() + response, err := service.ListCurrencies( + service.WithListCurrenciesTotal(false), + ) fmt.Println(response, err) } ``` diff --git a/docs/examples/locale/list-languages.md b/docs/examples/locale/list-languages.md index 3806001b..98e8bc9b 100644 --- a/docs/examples/locale/list-languages.md +++ b/docs/examples/locale/list-languages.md @@ -17,7 +17,9 @@ func main() { service := locale.New(client) - response, err := service.ListLanguages() + response, err := service.ListLanguages( + service.WithListLanguagesTotal(false), + ) fmt.Println(response, err) } ``` diff --git a/docs/examples/messaging/create-push.md b/docs/examples/messaging/create-push.md index 70659949..e1ca0fa4 100644 --- a/docs/examples/messaging/create-push.md +++ b/docs/examples/messaging/create-push.md @@ -37,6 +37,7 @@ func main() { service.WithCreatePushContentAvailable(false), service.WithCreatePushCritical(false), service.WithCreatePushPriority("normal"), + service.WithCreatePushChannelId(""), ) fmt.Println(response, err) } diff --git a/docs/examples/messaging/update-email.md b/docs/examples/messaging/update-email.md index 05ff62a7..5b26875b 100644 --- a/docs/examples/messaging/update-email.md +++ b/docs/examples/messaging/update-email.md @@ -19,19 +19,19 @@ func main() { response, err := service.UpdateEmail( "", + service.WithUpdateEmailSubject(""), + service.WithUpdateEmailContent(""), service.WithUpdateEmailTopics([]string{"example"}), service.WithUpdateEmailUsers([]string{"example"}), service.WithUpdateEmailTargets([]string{"example"}), - service.WithUpdateEmailSubject(""), - service.WithUpdateEmailContent(""), - service.WithUpdateEmailDraft(false), - service.WithUpdateEmailHtml(false), service.WithUpdateEmailCc([]string{"example"}), service.WithUpdateEmailBcc([]string{"example"}), + service.WithUpdateEmailAttachments([]string{"example"}), service.WithUpdateEmailReplyToEmail("email@example.com"), service.WithUpdateEmailReplyToName(""), + service.WithUpdateEmailDraft(false), + service.WithUpdateEmailHtml(false), service.WithUpdateEmailScheduledAt("2020-10-15T06:38:00.000+00:00"), - service.WithUpdateEmailAttachments([]string{"example"}), ) fmt.Println(response, err) } diff --git a/docs/examples/messaging/update-push.md b/docs/examples/messaging/update-push.md index 8d3b933a..450567c8 100644 --- a/docs/examples/messaging/update-push.md +++ b/docs/examples/messaging/update-push.md @@ -19,11 +19,11 @@ func main() { response, err := service.UpdatePush( "", + service.WithUpdatePushTitle(""), + service.WithUpdatePushBody("<BODY>"), service.WithUpdatePushTopics([]string{"example"}), service.WithUpdatePushUsers([]string{"example"}), service.WithUpdatePushTargets([]string{"example"}), - service.WithUpdatePushTitle("<TITLE>"), - service.WithUpdatePushBody("<BODY>"), service.WithUpdatePushData([]interface{}{}), service.WithUpdatePushAction("<ACTION>"), service.WithUpdatePushImage("<ID1:ID2>"), @@ -37,6 +37,7 @@ func main() { service.WithUpdatePushContentAvailable(false), service.WithUpdatePushCritical(false), service.WithUpdatePushPriority("normal"), + service.WithUpdatePushChannelId("<CHANNEL_ID>"), ) fmt.Println(response, err) } diff --git a/docs/examples/messaging/update-sms.md b/docs/examples/messaging/update-sms.md index 22f60b3d..9503eb80 100644 --- a/docs/examples/messaging/update-sms.md +++ b/docs/examples/messaging/update-sms.md @@ -19,10 +19,10 @@ func main() { response, err := service.UpdateSMS( "<MESSAGE_ID>", + service.WithUpdateSMSContent("<CONTENT>"), service.WithUpdateSMSTopics([]string{"example"}), service.WithUpdateSMSUsers([]string{"example"}), service.WithUpdateSMSTargets([]string{"example"}), - service.WithUpdateSMSContent("<CONTENT>"), service.WithUpdateSMSDraft(false), service.WithUpdateSMSScheduledAt("2020-10-15T06:38:00.000+00:00"), ) diff --git a/docs/examples/project/update-o-auth-2-webflow.md b/docs/examples/project/update-o-auth-2-webflow.md new file mode 100644 index 00000000..1c8d8d3a --- /dev/null +++ b/docs/examples/project/update-o-auth-2-webflow.md @@ -0,0 +1,27 @@ +```go +package main + +import ( + "fmt" + + "github.com/appwrite/sdk-for-go/v7/appwrite" + "github.com/appwrite/sdk-for-go/v7/project" +) + +func main() { + client := appwrite.NewClient( + appwrite.WithEndpoint("https://<REGION>.cloud.appwrite.io/v1"), + appwrite.WithProject("<YOUR_PROJECT_ID>"), + appwrite.WithKey("<YOUR_API_KEY>"), + ) + + service := project.New(client) + + response, err := service.UpdateOAuth2Webflow( + service.WithUpdateOAuth2WebflowClientId("<CLIENT_ID>"), + service.WithUpdateOAuth2WebflowClientSecret("<CLIENT_SECRET>"), + service.WithUpdateOAuth2WebflowEnabled(false), + ) + fmt.Println(response, err) +} +``` diff --git a/docs/examples/sites/list-frameworks.md b/docs/examples/sites/list-frameworks.md index 6862114f..96829e8b 100644 --- a/docs/examples/sites/list-frameworks.md +++ b/docs/examples/sites/list-frameworks.md @@ -17,7 +17,9 @@ func main() { service := sites.New(client) - response, err := service.ListFrameworks() + response, err := service.ListFrameworks( + service.WithListFrameworksTotal(false), + ) fmt.Println(response, err) } ``` diff --git a/docs/examples/sites/list-specifications.md b/docs/examples/sites/list-specifications.md index ef95d028..c3279c24 100644 --- a/docs/examples/sites/list-specifications.md +++ b/docs/examples/sites/list-specifications.md @@ -19,6 +19,7 @@ func main() { response, err := service.ListSpecifications( service.WithListSpecificationsType("runtimes"), + service.WithListSpecificationsTotal(false), ) fmt.Println(response, err) } diff --git a/docs/examples/tablesdb/list-transactions.md b/docs/examples/tablesdb/list-transactions.md index e5019450..0f3da4bf 100644 --- a/docs/examples/tablesdb/list-transactions.md +++ b/docs/examples/tablesdb/list-transactions.md @@ -19,6 +19,7 @@ func main() { response, err := service.ListTransactions( service.WithListTransactionsQueries([]string{"example"}), + service.WithListTransactionsTotal(false), ) fmt.Println(response, err) } diff --git a/docs/examples/vectorsdb/list-transactions.md b/docs/examples/vectorsdb/list-transactions.md index 5d70bdd0..1789ed9d 100644 --- a/docs/examples/vectorsdb/list-transactions.md +++ b/docs/examples/vectorsdb/list-transactions.md @@ -19,6 +19,7 @@ func main() { response, err := service.ListTransactions( service.WithListTransactionsQueries([]string{"example"}), + service.WithListTransactionsTotal(false), ) fmt.Println(response, err) } diff --git a/documentsdb/documents_db.go b/documentsdb/documents_db.go index fbe8b229..27bac2d7 100644 --- a/documentsdb/documents_db.go +++ b/documentsdb/documents_db.go @@ -228,11 +228,12 @@ func (srv *DocumentsDB) ListSpecifications() (*models.DedicatedDatabaseSpecifica type ListTransactionsOptions struct { Queries []string + Total bool enabledSetters map[string]bool } func (options ListTransactionsOptions) New() *ListTransactionsOptions { - options.enabledSetters = map[string]bool{"Queries": false} + options.enabledSetters = map[string]bool{"Queries": false, "Total": false} return &options } @@ -244,6 +245,12 @@ func (srv *DocumentsDB) WithListTransactionsQueries(v []string) ListTransactions o.enabledSetters["Queries"] = true } } +func (srv *DocumentsDB) WithListTransactionsTotal(v bool) ListTransactionsOption { + return func(o *ListTransactionsOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} // ListTransactions list transactions across all databases. func (srv *DocumentsDB) ListTransactions(optionalSetters ...ListTransactionsOption) (*models.TransactionList, error) { @@ -256,6 +263,9 @@ func (srv *DocumentsDB) ListTransactions(optionalSetters ...ListTransactionsOpti if options.enabledSetters["Queries"] { params["queries"] = options.Queries } + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" diff --git a/documentsdb/documents_db_test.go b/documentsdb/documents_db_test.go index 3fd356d1..38fa3cf5 100644 --- a/documentsdb/documents_db_test.go +++ b/documentsdb/documents_db_test.go @@ -1320,10 +1320,6 @@ func TestDocumentsDB(t *testing.T) { "engine": "postgresql", "version": "17", "uptime": 86400, - "connections": { - "current": 12, - "max": 100 - }, "syncMode": "async", "syncDegraded": true, "syncAcknowledgements": 1, diff --git a/domains/domains.go b/domains/domains.go index ece92326..f4bc23c4 100644 --- a/domains/domains.go +++ b/domains/domains.go @@ -2812,7 +2812,7 @@ func (srv *Domains) GetTransferStatus(DomainId string) (*models.DomainTransferSt // return the DNS // zone file in a standardized format that can be used to configure DNS // servers. -func (srv *Domains) GetZone(DomainId string) (*interface{}, error) { +func (srv *Domains) GetZone(DomainId string) (*string, error) { if DomainId == "" { return nil, errors.New("Missing required parameter: \"domainId\"") } @@ -2828,25 +2828,11 @@ func (srv *Domains) GetZone(DomainId string) (*interface{}, error) { if err != nil { return nil, err } - if strings.HasPrefix(resp.Type, "application/json") { - bytes, err := client.ResponseBody(resp) - if err != nil { - return nil, err - } - - var parsed interface{} - - err = json.Unmarshal(bytes, &parsed) - if err != nil { - return nil, err - } - return &parsed, nil - } - var parsed interface{} - parsed, ok := resp.Result.(interface{}) - if !ok { - return nil, errors.New("unexpected response type") + body, err := client.ResponseBody(resp) + if err != nil { + return nil, err } + parsed := string(body) return &parsed, nil } diff --git a/domains/domains_test.go b/domains/domains_test.go index 60e3202d..cf027d5c 100644 --- a/domains/domains_test.go +++ b/domains/domains_test.go @@ -951,7 +951,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.CreateRecordA("<DOMAIN_ID>", "", "", 1) + _, err := srv.CreateRecordA("<DOMAIN_ID>", "name", "value", 1) if err != nil { t.Errorf("Method CreateRecordA failed: %v", err) } @@ -988,7 +988,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.UpdateRecordA("<DOMAIN_ID>", "<RECORD_ID>", "", "", 1) + _, err := srv.UpdateRecordA("<DOMAIN_ID>", "<RECORD_ID>", "name", "value", 1) if err != nil { t.Errorf("Method UpdateRecordA failed: %v", err) } @@ -1025,7 +1025,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.CreateRecordAAAA("<DOMAIN_ID>", "", "", 1) + _, err := srv.CreateRecordAAAA("<DOMAIN_ID>", "name", "value", 1) if err != nil { t.Errorf("Method CreateRecordAAAA failed: %v", err) } @@ -1062,7 +1062,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.UpdateRecordAAAA("<DOMAIN_ID>", "<RECORD_ID>", "", "", 1) + _, err := srv.UpdateRecordAAAA("<DOMAIN_ID>", "<RECORD_ID>", "name", "value", 1) if err != nil { t.Errorf("Method UpdateRecordAAAA failed: %v", err) } @@ -1099,7 +1099,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.CreateRecordAlias("<DOMAIN_ID>", "", "<VALUE>", 1) + _, err := srv.CreateRecordAlias("<DOMAIN_ID>", "name", "<VALUE>", 1) if err != nil { t.Errorf("Method CreateRecordAlias failed: %v", err) } @@ -1136,7 +1136,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.UpdateRecordAlias("<DOMAIN_ID>", "<RECORD_ID>", "", "<VALUE>", 1) + _, err := srv.UpdateRecordAlias("<DOMAIN_ID>", "<RECORD_ID>", "name", "<VALUE>", 1) if err != nil { t.Errorf("Method UpdateRecordAlias failed: %v", err) } @@ -1173,7 +1173,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.CreateRecordCAA("<DOMAIN_ID>", "", "", 1) + _, err := srv.CreateRecordCAA("<DOMAIN_ID>", "name", "value", 1) if err != nil { t.Errorf("Method CreateRecordCAA failed: %v", err) } @@ -1210,7 +1210,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.UpdateRecordCAA("<DOMAIN_ID>", "<RECORD_ID>", "", "", 1) + _, err := srv.UpdateRecordCAA("<DOMAIN_ID>", "<RECORD_ID>", "name", "value", 1) if err != nil { t.Errorf("Method UpdateRecordCAA failed: %v", err) } @@ -1247,7 +1247,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.CreateRecordCNAME("<DOMAIN_ID>", "", "<VALUE>", 1) + _, err := srv.CreateRecordCNAME("<DOMAIN_ID>", "name", "<VALUE>", 1) if err != nil { t.Errorf("Method CreateRecordCNAME failed: %v", err) } @@ -1284,7 +1284,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.UpdateRecordCNAME("<DOMAIN_ID>", "<RECORD_ID>", "", "<VALUE>", 1) + _, err := srv.UpdateRecordCNAME("<DOMAIN_ID>", "<RECORD_ID>", "name", "<VALUE>", 1) if err != nil { t.Errorf("Method UpdateRecordCNAME failed: %v", err) } @@ -1321,7 +1321,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.CreateRecordHTTPS("<DOMAIN_ID>", "", "<VALUE>", 1) + _, err := srv.CreateRecordHTTPS("<DOMAIN_ID>", "name", "<VALUE>", 1) if err != nil { t.Errorf("Method CreateRecordHTTPS failed: %v", err) } @@ -1358,7 +1358,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.UpdateRecordHTTPS("<DOMAIN_ID>", "<RECORD_ID>", "", "<VALUE>", 1) + _, err := srv.UpdateRecordHTTPS("<DOMAIN_ID>", "<RECORD_ID>", "name", "<VALUE>", 1) if err != nil { t.Errorf("Method UpdateRecordHTTPS failed: %v", err) } @@ -1395,7 +1395,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.CreateRecordMX("<DOMAIN_ID>", "", "<VALUE>", 1, 1) + _, err := srv.CreateRecordMX("<DOMAIN_ID>", "name", "<VALUE>", 1, 1) if err != nil { t.Errorf("Method CreateRecordMX failed: %v", err) } @@ -1432,7 +1432,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.UpdateRecordMX("<DOMAIN_ID>", "<RECORD_ID>", "", "<VALUE>", 1, 1) + _, err := srv.UpdateRecordMX("<DOMAIN_ID>", "<RECORD_ID>", "name", "<VALUE>", 1, 1) if err != nil { t.Errorf("Method UpdateRecordMX failed: %v", err) } @@ -1469,7 +1469,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.CreateRecordNS("<DOMAIN_ID>", "", "<VALUE>", 1) + _, err := srv.CreateRecordNS("<DOMAIN_ID>", "name", "<VALUE>", 1) if err != nil { t.Errorf("Method CreateRecordNS failed: %v", err) } @@ -1506,7 +1506,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.UpdateRecordNS("<DOMAIN_ID>", "<RECORD_ID>", "", "<VALUE>", 1) + _, err := srv.UpdateRecordNS("<DOMAIN_ID>", "<RECORD_ID>", "name", "<VALUE>", 1) if err != nil { t.Errorf("Method UpdateRecordNS failed: %v", err) } @@ -1543,7 +1543,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.CreateRecordSRV("<DOMAIN_ID>", "", "<VALUE>", 1, 1, 1, 1) + _, err := srv.CreateRecordSRV("<DOMAIN_ID>", "name", "<VALUE>", 1, 1, 1, 1) if err != nil { t.Errorf("Method CreateRecordSRV failed: %v", err) } @@ -1580,7 +1580,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.UpdateRecordSRV("<DOMAIN_ID>", "<RECORD_ID>", "", "<VALUE>", 1, 1, 1, 1) + _, err := srv.UpdateRecordSRV("<DOMAIN_ID>", "<RECORD_ID>", "name", "<VALUE>", 1, 1, 1, 1) if err != nil { t.Errorf("Method UpdateRecordSRV failed: %v", err) } @@ -1617,7 +1617,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.CreateRecordTXT("<DOMAIN_ID>", "", 1) + _, err := srv.CreateRecordTXT("<DOMAIN_ID>", "name", 1) if err != nil { t.Errorf("Method CreateRecordTXT failed: %v", err) } @@ -1654,7 +1654,7 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.UpdateRecordTXT("<DOMAIN_ID>", "<RECORD_ID>", "", "<VALUE>", 1) + _, err := srv.UpdateRecordTXT("<DOMAIN_ID>", "<RECORD_ID>", "name", "<VALUE>", 1) if err != nil { t.Errorf("Method UpdateRecordTXT failed: %v", err) } @@ -1804,18 +1804,14 @@ func TestDomains(t *testing.T) { }) t.Run("Test GetZone", func(t *testing.T) { - mockResponse := ` -{ - "message": "success" -} -` + mockResponse := "; café zone\nwww 3600 IN A 192.0.2.1\n" ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { t.Errorf("Expected method GET, got %s", r.Method) } - w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(mockResponse)) })) @@ -1823,10 +1819,13 @@ func TestDomains(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.GetZone("<DOMAIN_ID>") + response, err := srv.GetZone("<DOMAIN_ID>") if err != nil { t.Errorf("Method GetZone failed: %v", err) } + if response == nil || *response != mockResponse { + t.Errorf("Expected exact text %q, got %v", mockResponse, response) + } }) t.Run("Test UpdateZone", func(t *testing.T) { diff --git a/functions/functions.go b/functions/functions.go index 302be1cf..5ca1cf5d 100644 --- a/functions/functions.go +++ b/functions/functions.go @@ -354,11 +354,37 @@ func (srv *Functions) Create(FunctionId string, Name string, Runtime string, opt } +type ListRuntimesOptions struct { + Total bool + enabledSetters map[string]bool +} + +func (options ListRuntimesOptions) New() *ListRuntimesOptions { + options.enabledSetters = map[string]bool{"Total": false} + return &options +} + +type ListRuntimesOption func(*ListRuntimesOptions) + +func (srv *Functions) WithListRuntimesTotal(v bool) ListRuntimesOption { + return func(o *ListRuntimesOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} + // ListRuntimes get a list of all runtimes that are currently active on your // instance. -func (srv *Functions) ListRuntimes() (*models.RuntimeList, error) { +func (srv *Functions) ListRuntimes(optionalSetters ...ListRuntimesOption) (*models.RuntimeList, error) { path := "/functions/runtimes" + options := ListRuntimesOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } params := map[string]interface{}{} + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" @@ -393,11 +419,12 @@ func (srv *Functions) ListRuntimes() (*models.RuntimeList, error) { type ListSpecificationsOptions struct { Type string + Total bool enabledSetters map[string]bool } func (options ListSpecificationsOptions) New() *ListSpecificationsOptions { - options.enabledSetters = map[string]bool{"Type": false} + options.enabledSetters = map[string]bool{"Type": false, "Total": false} return &options } @@ -409,6 +436,12 @@ func (srv *Functions) WithListSpecificationsType(v string) ListSpecificationsOpt o.enabledSetters["Type"] = true } } +func (srv *Functions) WithListSpecificationsTotal(v bool) ListSpecificationsOption { + return func(o *ListSpecificationsOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} // ListSpecifications list allowed function specifications for this instance. func (srv *Functions) ListSpecifications(optionalSetters ...ListSpecificationsOption) (*models.SpecificationList, error) { @@ -421,6 +454,9 @@ func (srv *Functions) ListSpecifications(optionalSetters ...ListSpecificationsOp if options.enabledSetters["Type"] { params["type"] = options.Type } + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" @@ -993,7 +1029,7 @@ func (srv *Functions) CreateDeployment(FunctionId string, Code file.InputFile, A uploadId := "" - resp, err := srv.client.FileUpload(path, headers, params, paramName, uploadId) + resp, err := srv.client.FileUpload(path, headers, params, paramName, uploadId, "POST") if err != nil { return nil, err } @@ -1002,12 +1038,11 @@ func (srv *Functions) CreateDeployment(FunctionId string, Code file.InputFile, A if err != nil { return nil, err } - var parsed models.Deployment - err = json.Unmarshal(bytes, &parsed) - if err != nil { + parsed := models.Deployment{}.New(bytes) + if err := json.Unmarshal(bytes, parsed); err != nil { return nil, err } - return &parsed, nil + return parsed, nil } var parsed models.Deployment parsed, ok := resp.Result.(models.Deployment) diff --git a/locale/locale.go b/locale/locale.go index eed073cb..53e2ed7a 100644 --- a/locale/locale.go +++ b/locale/locale.go @@ -61,11 +61,37 @@ func (srv *Locale) Get() (*models.Locale, error) { } +type ListCodesOptions struct { + Total bool + enabledSetters map[string]bool +} + +func (options ListCodesOptions) New() *ListCodesOptions { + options.enabledSetters = map[string]bool{"Total": false} + return &options +} + +type ListCodesOption func(*ListCodesOptions) + +func (srv *Locale) WithListCodesTotal(v bool) ListCodesOption { + return func(o *ListCodesOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} + // ListCodes list of all locale codes in [ISO // 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). -func (srv *Locale) ListCodes() (*models.LocaleCodeList, error) { +func (srv *Locale) ListCodes(optionalSetters ...ListCodesOption) (*models.LocaleCodeList, error) { path := "/locale/codes" + options := ListCodesOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } params := map[string]interface{}{} + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" @@ -98,11 +124,37 @@ func (srv *Locale) ListCodes() (*models.LocaleCodeList, error) { } +type ListContinentsOptions struct { + Total bool + enabledSetters map[string]bool +} + +func (options ListContinentsOptions) New() *ListContinentsOptions { + options.enabledSetters = map[string]bool{"Total": false} + return &options +} + +type ListContinentsOption func(*ListContinentsOptions) + +func (srv *Locale) WithListContinentsTotal(v bool) ListContinentsOption { + return func(o *ListContinentsOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} + // ListContinents list of all continents. You can use the locale header to get // the data in a supported language. -func (srv *Locale) ListContinents() (*models.ContinentList, error) { +func (srv *Locale) ListContinents(optionalSetters ...ListContinentsOption) (*models.ContinentList, error) { path := "/locale/continents" + options := ListContinentsOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } params := map[string]interface{}{} + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" @@ -135,11 +187,37 @@ func (srv *Locale) ListContinents() (*models.ContinentList, error) { } +type ListCountriesOptions struct { + Total bool + enabledSetters map[string]bool +} + +func (options ListCountriesOptions) New() *ListCountriesOptions { + options.enabledSetters = map[string]bool{"Total": false} + return &options +} + +type ListCountriesOption func(*ListCountriesOptions) + +func (srv *Locale) WithListCountriesTotal(v bool) ListCountriesOption { + return func(o *ListCountriesOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} + // ListCountries list of all countries. You can use the locale header to get // the data in a supported language. -func (srv *Locale) ListCountries() (*models.CountryList, error) { +func (srv *Locale) ListCountries(optionalSetters ...ListCountriesOption) (*models.CountryList, error) { path := "/locale/countries" + options := ListCountriesOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } params := map[string]interface{}{} + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" @@ -172,11 +250,37 @@ func (srv *Locale) ListCountries() (*models.CountryList, error) { } +type ListCountriesEUOptions struct { + Total bool + enabledSetters map[string]bool +} + +func (options ListCountriesEUOptions) New() *ListCountriesEUOptions { + options.enabledSetters = map[string]bool{"Total": false} + return &options +} + +type ListCountriesEUOption func(*ListCountriesEUOptions) + +func (srv *Locale) WithListCountriesEUTotal(v bool) ListCountriesEUOption { + return func(o *ListCountriesEUOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} + // ListCountriesEU list of all countries that are currently members of the EU. // You can use the locale header to get the data in a supported language. -func (srv *Locale) ListCountriesEU() (*models.CountryList, error) { +func (srv *Locale) ListCountriesEU(optionalSetters ...ListCountriesEUOption) (*models.CountryList, error) { path := "/locale/countries/eu" + options := ListCountriesEUOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } params := map[string]interface{}{} + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" @@ -209,11 +313,37 @@ func (srv *Locale) ListCountriesEU() (*models.CountryList, error) { } +type ListCountriesPhonesOptions struct { + Total bool + enabledSetters map[string]bool +} + +func (options ListCountriesPhonesOptions) New() *ListCountriesPhonesOptions { + options.enabledSetters = map[string]bool{"Total": false} + return &options +} + +type ListCountriesPhonesOption func(*ListCountriesPhonesOptions) + +func (srv *Locale) WithListCountriesPhonesTotal(v bool) ListCountriesPhonesOption { + return func(o *ListCountriesPhonesOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} + // ListCountriesPhones list of all countries phone codes. You can use the // locale header to get the data in a supported language. -func (srv *Locale) ListCountriesPhones() (*models.PhoneList, error) { +func (srv *Locale) ListCountriesPhones(optionalSetters ...ListCountriesPhonesOption) (*models.PhoneList, error) { path := "/locale/countries/phones" + options := ListCountriesPhonesOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } params := map[string]interface{}{} + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" @@ -246,12 +376,38 @@ func (srv *Locale) ListCountriesPhones() (*models.PhoneList, error) { } +type ListCurrenciesOptions struct { + Total bool + enabledSetters map[string]bool +} + +func (options ListCurrenciesOptions) New() *ListCurrenciesOptions { + options.enabledSetters = map[string]bool{"Total": false} + return &options +} + +type ListCurrenciesOption func(*ListCurrenciesOptions) + +func (srv *Locale) WithListCurrenciesTotal(v bool) ListCurrenciesOption { + return func(o *ListCurrenciesOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} + // ListCurrencies list of all currencies, including currency symbol, name, // plural, and decimal digits for all major and minor currencies. You can use // the locale header to get the data in a supported language. -func (srv *Locale) ListCurrencies() (*models.CurrencyList, error) { +func (srv *Locale) ListCurrencies(optionalSetters ...ListCurrenciesOption) (*models.CurrencyList, error) { path := "/locale/currencies" + options := ListCurrenciesOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } params := map[string]interface{}{} + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" @@ -284,11 +440,37 @@ func (srv *Locale) ListCurrencies() (*models.CurrencyList, error) { } +type ListLanguagesOptions struct { + Total bool + enabledSetters map[string]bool +} + +func (options ListLanguagesOptions) New() *ListLanguagesOptions { + options.enabledSetters = map[string]bool{"Total": false} + return &options +} + +type ListLanguagesOption func(*ListLanguagesOptions) + +func (srv *Locale) WithListLanguagesTotal(v bool) ListLanguagesOption { + return func(o *ListLanguagesOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} + // ListLanguages list of all languages classified by ISO 639-1 including // 2-letter code, name in English, and name in the respective language. -func (srv *Locale) ListLanguages() (*models.LanguageList, error) { +func (srv *Locale) ListLanguages(optionalSetters ...ListLanguagesOption) (*models.LanguageList, error) { path := "/locale/languages" + options := ListLanguagesOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } params := map[string]interface{}{} + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" diff --git a/messaging/messaging.go b/messaging/messaging.go index 349ede54..73a554df 100644 --- a/messaging/messaging.go +++ b/messaging/messaging.go @@ -269,47 +269,29 @@ func (srv *Messaging) CreateEmail(MessageId string, Subject string, Content stri } type UpdateEmailOptions struct { + Subject string + Content string Topics []string Users []string Targets []string - Subject string - Content string - Draft bool - Html bool Cc []string Bcc []string + Attachments []string ReplyToEmail string ReplyToName string + Draft bool + Html bool ScheduledAt string - Attachments []string enabledSetters map[string]bool } func (options UpdateEmailOptions) New() *UpdateEmailOptions { - options.enabledSetters = map[string]bool{"Topics": false, "Users": false, "Targets": false, "Subject": false, "Content": false, "Draft": false, "Html": false, "Cc": false, "Bcc": false, "ReplyToEmail": false, "ReplyToName": false, "ScheduledAt": false, "Attachments": false} + options.enabledSetters = map[string]bool{"Subject": false, "Content": false, "Topics": false, "Users": false, "Targets": false, "Cc": false, "Bcc": false, "Attachments": false, "ReplyToEmail": false, "ReplyToName": false, "Draft": false, "Html": false, "ScheduledAt": false} return &options } type UpdateEmailOption func(*UpdateEmailOptions) -func (srv *Messaging) WithUpdateEmailTopics(v []string) UpdateEmailOption { - return func(o *UpdateEmailOptions) { - o.Topics = v - o.enabledSetters["Topics"] = true - } -} -func (srv *Messaging) WithUpdateEmailUsers(v []string) UpdateEmailOption { - return func(o *UpdateEmailOptions) { - o.Users = v - o.enabledSetters["Users"] = true - } -} -func (srv *Messaging) WithUpdateEmailTargets(v []string) UpdateEmailOption { - return func(o *UpdateEmailOptions) { - o.Targets = v - o.enabledSetters["Targets"] = true - } -} func (srv *Messaging) WithUpdateEmailSubject(v string) UpdateEmailOption { return func(o *UpdateEmailOptions) { o.Subject = v @@ -322,16 +304,22 @@ func (srv *Messaging) WithUpdateEmailContent(v string) UpdateEmailOption { o.enabledSetters["Content"] = true } } -func (srv *Messaging) WithUpdateEmailDraft(v bool) UpdateEmailOption { +func (srv *Messaging) WithUpdateEmailTopics(v []string) UpdateEmailOption { return func(o *UpdateEmailOptions) { - o.Draft = v - o.enabledSetters["Draft"] = true + o.Topics = v + o.enabledSetters["Topics"] = true } } -func (srv *Messaging) WithUpdateEmailHtml(v bool) UpdateEmailOption { +func (srv *Messaging) WithUpdateEmailUsers(v []string) UpdateEmailOption { return func(o *UpdateEmailOptions) { - o.Html = v - o.enabledSetters["Html"] = true + o.Users = v + o.enabledSetters["Users"] = true + } +} +func (srv *Messaging) WithUpdateEmailTargets(v []string) UpdateEmailOption { + return func(o *UpdateEmailOptions) { + o.Targets = v + o.enabledSetters["Targets"] = true } } func (srv *Messaging) WithUpdateEmailCc(v []string) UpdateEmailOption { @@ -346,6 +334,12 @@ func (srv *Messaging) WithUpdateEmailBcc(v []string) UpdateEmailOption { o.enabledSetters["Bcc"] = true } } +func (srv *Messaging) WithUpdateEmailAttachments(v []string) UpdateEmailOption { + return func(o *UpdateEmailOptions) { + o.Attachments = v + o.enabledSetters["Attachments"] = true + } +} func (srv *Messaging) WithUpdateEmailReplyToEmail(v string) UpdateEmailOption { return func(o *UpdateEmailOptions) { o.ReplyToEmail = v @@ -358,16 +352,22 @@ func (srv *Messaging) WithUpdateEmailReplyToName(v string) UpdateEmailOption { o.enabledSetters["ReplyToName"] = true } } -func (srv *Messaging) WithUpdateEmailScheduledAt(v string) UpdateEmailOption { +func (srv *Messaging) WithUpdateEmailDraft(v bool) UpdateEmailOption { return func(o *UpdateEmailOptions) { - o.ScheduledAt = v - o.enabledSetters["ScheduledAt"] = true + o.Draft = v + o.enabledSetters["Draft"] = true } } -func (srv *Messaging) WithUpdateEmailAttachments(v []string) UpdateEmailOption { +func (srv *Messaging) WithUpdateEmailHtml(v bool) UpdateEmailOption { return func(o *UpdateEmailOptions) { - o.Attachments = v - o.enabledSetters["Attachments"] = true + o.Html = v + o.enabledSetters["Html"] = true + } +} +func (srv *Messaging) WithUpdateEmailScheduledAt(v string) UpdateEmailOption { + return func(o *UpdateEmailOptions) { + o.ScheduledAt = v + o.enabledSetters["ScheduledAt"] = true } } @@ -386,6 +386,12 @@ func (srv *Messaging) UpdateEmail(MessageId string, optionalSetters ...UpdateEma opt(options) } params := map[string]interface{}{} + if options.enabledSetters["Subject"] { + params["subject"] = options.Subject + } + if options.enabledSetters["Content"] { + params["content"] = options.Content + } if options.enabledSetters["Topics"] { params["topics"] = options.Topics } @@ -395,36 +401,30 @@ func (srv *Messaging) UpdateEmail(MessageId string, optionalSetters ...UpdateEma if options.enabledSetters["Targets"] { params["targets"] = options.Targets } - if options.enabledSetters["Subject"] { - params["subject"] = options.Subject - } - if options.enabledSetters["Content"] { - params["content"] = options.Content - } - if options.enabledSetters["Draft"] { - params["draft"] = options.Draft - } - if options.enabledSetters["Html"] { - params["html"] = options.Html - } if options.enabledSetters["Cc"] { params["cc"] = options.Cc } if options.enabledSetters["Bcc"] { params["bcc"] = options.Bcc } + if options.enabledSetters["Attachments"] { + params["attachments"] = options.Attachments + } if options.enabledSetters["ReplyToEmail"] { params["replyToEmail"] = options.ReplyToEmail } if options.enabledSetters["ReplyToName"] { params["replyToName"] = options.ReplyToName } + if options.enabledSetters["Draft"] { + params["draft"] = options.Draft + } + if options.enabledSetters["Html"] { + params["html"] = options.Html + } if options.enabledSetters["ScheduledAt"] { params["scheduledAt"] = options.ScheduledAt } - if options.enabledSetters["Attachments"] { - params["attachments"] = options.Attachments - } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["content-type"] = "application/json" @@ -477,11 +477,12 @@ type CreatePushOptions struct { ContentAvailable bool Critical bool Priority string + ChannelId string enabledSetters map[string]bool } func (options CreatePushOptions) New() *CreatePushOptions { - options.enabledSetters = map[string]bool{"Title": false, "Body": false, "Topics": false, "Users": false, "Targets": false, "Data": false, "Action": false, "Image": false, "Icon": false, "Sound": false, "Color": false, "Tag": false, "Badge": false, "Draft": false, "ScheduledAt": false, "ContentAvailable": false, "Critical": false, "Priority": false} + options.enabledSetters = map[string]bool{"Title": false, "Body": false, "Topics": false, "Users": false, "Targets": false, "Data": false, "Action": false, "Image": false, "Icon": false, "Sound": false, "Color": false, "Tag": false, "Badge": false, "Draft": false, "ScheduledAt": false, "ContentAvailable": false, "Critical": false, "Priority": false, "ChannelId": false} return &options } @@ -595,6 +596,12 @@ func (srv *Messaging) WithCreatePushPriority(v string) CreatePushOption { o.enabledSetters["Priority"] = true } } +func (srv *Messaging) WithCreatePushChannelId(v string) CreatePushOption { + return func(o *CreatePushOptions) { + o.ChannelId = v + o.enabledSetters["ChannelId"] = true + } +} // CreatePush create a new push notification. func (srv *Messaging) CreatePush(MessageId string, optionalSetters ...CreatePushOption) (*models.Message, error) { @@ -659,6 +666,9 @@ func (srv *Messaging) CreatePush(MessageId string, optionalSetters ...CreatePush if options.enabledSetters["Priority"] { params["priority"] = options.Priority } + if options.enabledSetters["ChannelId"] { + params["channelId"] = options.ChannelId + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["content-type"] = "application/json" @@ -693,11 +703,11 @@ func (srv *Messaging) CreatePush(MessageId string, optionalSetters ...CreatePush } type UpdatePushOptions struct { + Title string + Body string Topics []string Users []string Targets []string - Title string - Body string Data interface{} Action string Image string @@ -711,16 +721,29 @@ type UpdatePushOptions struct { ContentAvailable bool Critical bool Priority string + ChannelId string enabledSetters map[string]bool } func (options UpdatePushOptions) New() *UpdatePushOptions { - options.enabledSetters = map[string]bool{"Topics": false, "Users": false, "Targets": false, "Title": false, "Body": false, "Data": false, "Action": false, "Image": false, "Icon": false, "Sound": false, "Color": false, "Tag": false, "Badge": false, "Draft": false, "ScheduledAt": false, "ContentAvailable": false, "Critical": false, "Priority": false} + options.enabledSetters = map[string]bool{"Title": false, "Body": false, "Topics": false, "Users": false, "Targets": false, "Data": false, "Action": false, "Image": false, "Icon": false, "Sound": false, "Color": false, "Tag": false, "Badge": false, "Draft": false, "ScheduledAt": false, "ContentAvailable": false, "Critical": false, "Priority": false, "ChannelId": false} return &options } type UpdatePushOption func(*UpdatePushOptions) +func (srv *Messaging) WithUpdatePushTitle(v string) UpdatePushOption { + return func(o *UpdatePushOptions) { + o.Title = v + o.enabledSetters["Title"] = true + } +} +func (srv *Messaging) WithUpdatePushBody(v string) UpdatePushOption { + return func(o *UpdatePushOptions) { + o.Body = v + o.enabledSetters["Body"] = true + } +} func (srv *Messaging) WithUpdatePushTopics(v []string) UpdatePushOption { return func(o *UpdatePushOptions) { o.Topics = v @@ -739,18 +762,6 @@ func (srv *Messaging) WithUpdatePushTargets(v []string) UpdatePushOption { o.enabledSetters["Targets"] = true } } -func (srv *Messaging) WithUpdatePushTitle(v string) UpdatePushOption { - return func(o *UpdatePushOptions) { - o.Title = v - o.enabledSetters["Title"] = true - } -} -func (srv *Messaging) WithUpdatePushBody(v string) UpdatePushOption { - return func(o *UpdatePushOptions) { - o.Body = v - o.enabledSetters["Body"] = true - } -} func (srv *Messaging) WithUpdatePushData(v interface{}) UpdatePushOption { return func(o *UpdatePushOptions) { o.Data = v @@ -829,6 +840,12 @@ func (srv *Messaging) WithUpdatePushPriority(v string) UpdatePushOption { o.enabledSetters["Priority"] = true } } +func (srv *Messaging) WithUpdatePushChannelId(v string) UpdatePushOption { + return func(o *UpdatePushOptions) { + o.ChannelId = v + o.enabledSetters["ChannelId"] = true + } +} // UpdatePush update a push notification by its unique ID. This endpoint only // works on messages that are in draft status. Messages that are already @@ -845,6 +862,12 @@ func (srv *Messaging) UpdatePush(MessageId string, optionalSetters ...UpdatePush opt(options) } params := map[string]interface{}{} + if options.enabledSetters["Title"] { + params["title"] = options.Title + } + if options.enabledSetters["Body"] { + params["body"] = options.Body + } if options.enabledSetters["Topics"] { params["topics"] = options.Topics } @@ -854,12 +877,6 @@ func (srv *Messaging) UpdatePush(MessageId string, optionalSetters ...UpdatePush if options.enabledSetters["Targets"] { params["targets"] = options.Targets } - if options.enabledSetters["Title"] { - params["title"] = options.Title - } - if options.enabledSetters["Body"] { - params["body"] = options.Body - } if options.enabledSetters["Data"] { params["data"] = options.Data } @@ -899,6 +916,9 @@ func (srv *Messaging) UpdatePush(MessageId string, optionalSetters ...UpdatePush if options.enabledSetters["Priority"] { params["priority"] = options.Priority } + if options.enabledSetters["ChannelId"] { + params["channelId"] = options.ChannelId + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["content-type"] = "application/json" @@ -1145,22 +1165,28 @@ func (srv *Messaging) CreateSMS(MessageId string, Content string, optionalSetter } type UpdateSmsOptions struct { + Content string Topics []string Users []string Targets []string - Content string Draft bool ScheduledAt string enabledSetters map[string]bool } func (options UpdateSmsOptions) New() *UpdateSmsOptions { - options.enabledSetters = map[string]bool{"Topics": false, "Users": false, "Targets": false, "Content": false, "Draft": false, "ScheduledAt": false} + options.enabledSetters = map[string]bool{"Content": false, "Topics": false, "Users": false, "Targets": false, "Draft": false, "ScheduledAt": false} return &options } type UpdateSmsOption func(*UpdateSmsOptions) +func (srv *Messaging) WithUpdateSmsContent(v string) UpdateSmsOption { + return func(o *UpdateSmsOptions) { + o.Content = v + o.enabledSetters["Content"] = true + } +} func (srv *Messaging) WithUpdateSmsTopics(v []string) UpdateSmsOption { return func(o *UpdateSmsOptions) { o.Topics = v @@ -1179,12 +1205,6 @@ func (srv *Messaging) WithUpdateSmsTargets(v []string) UpdateSmsOption { o.enabledSetters["Targets"] = true } } -func (srv *Messaging) WithUpdateSmsContent(v string) UpdateSmsOption { - return func(o *UpdateSmsOptions) { - o.Content = v - o.enabledSetters["Content"] = true - } -} func (srv *Messaging) WithUpdateSmsDraft(v bool) UpdateSmsOption { return func(o *UpdateSmsOptions) { o.Draft = v @@ -1215,6 +1235,9 @@ func (srv *Messaging) UpdateSms(MessageId string, optionalSetters ...UpdateSmsOp opt(options) } params := map[string]interface{}{} + if options.enabledSetters["Content"] { + params["content"] = options.Content + } if options.enabledSetters["Topics"] { params["topics"] = options.Topics } @@ -1224,9 +1247,6 @@ func (srv *Messaging) UpdateSms(MessageId string, optionalSetters ...UpdateSmsOp if options.enabledSetters["Targets"] { params["targets"] = options.Targets } - if options.enabledSetters["Content"] { - params["content"] = options.Content - } if options.enabledSetters["Draft"] { params["draft"] = options.Draft } @@ -1267,22 +1287,28 @@ func (srv *Messaging) UpdateSms(MessageId string, optionalSetters ...UpdateSmsOp } type UpdateSMSOptions struct { + Content string Topics []string Users []string Targets []string - Content string Draft bool ScheduledAt string enabledSetters map[string]bool } func (options UpdateSMSOptions) New() *UpdateSMSOptions { - options.enabledSetters = map[string]bool{"Topics": false, "Users": false, "Targets": false, "Content": false, "Draft": false, "ScheduledAt": false} + options.enabledSetters = map[string]bool{"Content": false, "Topics": false, "Users": false, "Targets": false, "Draft": false, "ScheduledAt": false} return &options } type UpdateSMSOption func(*UpdateSMSOptions) +func (srv *Messaging) WithUpdateSMSContent(v string) UpdateSMSOption { + return func(o *UpdateSMSOptions) { + o.Content = v + o.enabledSetters["Content"] = true + } +} func (srv *Messaging) WithUpdateSMSTopics(v []string) UpdateSMSOption { return func(o *UpdateSMSOptions) { o.Topics = v @@ -1301,12 +1327,6 @@ func (srv *Messaging) WithUpdateSMSTargets(v []string) UpdateSMSOption { o.enabledSetters["Targets"] = true } } -func (srv *Messaging) WithUpdateSMSContent(v string) UpdateSMSOption { - return func(o *UpdateSMSOptions) { - o.Content = v - o.enabledSetters["Content"] = true - } -} func (srv *Messaging) WithUpdateSMSDraft(v bool) UpdateSMSOption { return func(o *UpdateSMSOptions) { o.Draft = v @@ -1335,6 +1355,9 @@ func (srv *Messaging) UpdateSMS(MessageId string, optionalSetters ...UpdateSMSOp opt(options) } params := map[string]interface{}{} + if options.enabledSetters["Content"] { + params["content"] = options.Content + } if options.enabledSetters["Topics"] { params["topics"] = options.Topics } @@ -1344,9 +1367,6 @@ func (srv *Messaging) UpdateSMS(MessageId string, optionalSetters ...UpdateSMSOp if options.enabledSetters["Targets"] { params["targets"] = options.Targets } - if options.enabledSetters["Content"] { - params["content"] = options.Content - } if options.enabledSetters["Draft"] { params["draft"] = options.Draft } diff --git a/models/account.go b/models/account.go new file mode 100644 index 00000000..703c9e80 --- /dev/null +++ b/models/account.go @@ -0,0 +1,85 @@ +package models + +import ( + "encoding/json" + "errors" +) + +// Account Model +type Account struct { + // User ID. + Id string `json:"$id"` + // User creation date in ISO 8601 format. + CreatedAt string `json:"$createdAt"` + // User update date in ISO 8601 format. + UpdatedAt string `json:"$updatedAt"` + // User name. + Name string `json:"name"` + // User registration date in ISO 8601 format. + Registration string `json:"registration"` + // User status. Pass `true` for enabled and `false` for disabled. + Status bool `json:"status"` + // Labels for the user. + Labels []string `json:"labels"` + // Password update time in ISO 8601 format. + PasswordUpdate string `json:"passwordUpdate"` + // User email address. + Email string `json:"email"` + // User phone number in E.164 format. + Phone string `json:"phone"` + // Email verification status. + EmailVerification bool `json:"emailVerification"` + // Canonical form of the user email address. + EmailCanonical *string `json:"emailCanonical"` + // Whether the user email is from a free email provider. + EmailIsFree *bool `json:"emailIsFree"` + // Whether the user email is from a disposable email provider. + EmailIsDisposable *bool `json:"emailIsDisposable"` + // Whether the user email is from a corporate domain. + EmailIsCorporate *bool `json:"emailIsCorporate"` + // Whether the user email is in its canonical form. + EmailIsCanonical *bool `json:"emailIsCanonical"` + // Whether the password was found in a known data breach the last time it was + // checked. Null when the password has never been checked. + PasswordPwned *bool `json:"passwordPwned"` + // Phone verification status. + PhoneVerification bool `json:"phoneVerification"` + // Multi factor authentication status. + Mfa bool `json:"mfa"` + // User preferences as a key-value object + Prefs Preferences `json:"prefs"` + // A user-owned message receiver. A single user may have multiple e.g. emails, + // phones, and a browser. Each target is registered with a single provider. + Targets []Target `json:"targets"` + // Most recent access date in ISO 8601 format. This attribute is only updated + // again after 24 hours. + AccessedAt string `json:"accessedAt"` + // Whether the user can impersonate other users. + Impersonator *bool `json:"impersonator"` + // ID of the original actor performing the impersonation. Present only when + // the current request is impersonating another user. Internal audit logs + // attribute the action to this user, while the impersonated target is + // recorded only in internal audit payload data. + ImpersonatorUserId *string `json:"impersonatorUserId"` + + // Used by Decode() method + data []byte +} + +func (model Account) New(data []byte) *Account { + model.data = data + return &model +} + +func (model *Account) Decode(value interface{}) error { + if len(model.data) <= 0 { + return errors.New("method Decode() cannot be used on nested struct") + } + + err := json.Unmarshal(model.data, value) + if err != nil { + return err + } + + return nil +} diff --git a/models/account_test.go b/models/account_test.go new file mode 100644 index 00000000..223fbe22 --- /dev/null +++ b/models/account_test.go @@ -0,0 +1,60 @@ +package models + +import ( + "encoding/json" + "testing" +) + +func TestAccountModel(t *testing.T) { + model := Account{Id: "5e5ea5c16897e", CreatedAt: "2020-10-15T06:38:00.000+00:00", UpdatedAt: "2020-10-15T06:38:00.000+00:00", Name: "John Doe", Registration: "2020-10-15T06:38:00.000+00:00", Status: true, Labels: []string{"test"}, PasswordUpdate: "2020-10-15T06:38:00.000+00:00", Email: "john@appwrite.io", Phone: "+4930901820", EmailVerification: true, PhoneVerification: true, Mfa: true, Prefs: Preferences{}, Targets: []Target{Target{Id: "259125845563242502", CreatedAt: "2020-10-15T06:38:00.000+00:00", UpdatedAt: "2020-10-15T06:38:00.000+00:00", Name: "Apple iPhone 12", UserId: "259125845563242502", ProviderType: "email", Identifier: "token", Expired: true}}, AccessedAt: "2020-10-15T06:38:00.000+00:00"} + + data, err := json.Marshal(model) + if err != nil { + t.Fatal(err) + } + + var result Account + err = json.Unmarshal(data, &result) + if err != nil { + t.Fatal(err) + } + if result.Id != model.Id { + t.Errorf("Expected Id %v, got %v", model.Id, result.Id) + } + if result.CreatedAt != model.CreatedAt { + t.Errorf("Expected CreatedAt %v, got %v", model.CreatedAt, result.CreatedAt) + } + if result.UpdatedAt != model.UpdatedAt { + t.Errorf("Expected UpdatedAt %v, got %v", model.UpdatedAt, result.UpdatedAt) + } + if result.Name != model.Name { + t.Errorf("Expected Name %v, got %v", model.Name, result.Name) + } + if result.Registration != model.Registration { + t.Errorf("Expected Registration %v, got %v", model.Registration, result.Registration) + } + if result.Status != model.Status { + t.Errorf("Expected Status %v, got %v", model.Status, result.Status) + } + if result.PasswordUpdate != model.PasswordUpdate { + t.Errorf("Expected PasswordUpdate %v, got %v", model.PasswordUpdate, result.PasswordUpdate) + } + if result.Email != model.Email { + t.Errorf("Expected Email %v, got %v", model.Email, result.Email) + } + if result.Phone != model.Phone { + t.Errorf("Expected Phone %v, got %v", model.Phone, result.Phone) + } + if result.EmailVerification != model.EmailVerification { + t.Errorf("Expected EmailVerification %v, got %v", model.EmailVerification, result.EmailVerification) + } + if result.PhoneVerification != model.PhoneVerification { + t.Errorf("Expected PhoneVerification %v, got %v", model.PhoneVerification, result.PhoneVerification) + } + if result.Mfa != model.Mfa { + t.Errorf("Expected Mfa %v, got %v", model.Mfa, result.Mfa) + } + if result.AccessedAt != model.AccessedAt { + t.Errorf("Expected AccessedAt %v, got %v", model.AccessedAt, result.AccessedAt) + } +} diff --git a/models/analyticsMetric.go b/models/analyticsMetric.go new file mode 100644 index 00000000..fd4600bd --- /dev/null +++ b/models/analyticsMetric.go @@ -0,0 +1,67 @@ +package models + +import ( + "encoding/json" + "errors" +) + +// AnalyticsMetric Model +type AnalyticsMetric struct { + // Dimension value this row covers. Null when no dimension was requested, + // empty when the dimension could not be derived for those events. + Value *string `json:"value"` + // Start of the time bucket this row covers, in ISO 8601. Null when no + // interval was requested. + Date *string `json:"date"` + // Unique visitors in the requested range. + Visitors int `json:"visitors"` + // Unique sessions in the requested range. + Sessions int `json:"sessions"` + // Total pageview events (events with name="pageview") in the requested range. + // Only the flat aggregate computes it; null on breakdown and time-series + // rows. + Pageviews *int `json:"pageviews"` + // Total events in the requested range. + Events int `json:"events"` + // Total sessions with activity in the requested range. Only the flat + // aggregate computes it; null on breakdown and time-series rows. + Visits *int `json:"visits"` + // Share of single-event sessions, as a percentage. Only the flat aggregate + // computes it; null on breakdown and time-series rows. + BounceRate *float64 `json:"bounceRate"` + // Average session length in seconds, measured first event to last event. + // Single-event sessions count as 0. Only the flat aggregate computes it; null + // on breakdown and time-series rows. + VisitDuration *float64 `json:"visitDuration"` + // Average pageviews per session (pageviews divided by visits). Only the flat + // aggregate computes it; null on breakdown and time-series rows. + ViewsPerVisit *float64 `json:"viewsPerVisit"` + // Average scroll depth across events, as a percentage. Only the flat + // aggregate computes it; null on breakdown and time-series rows. + ScrollDepth *float64 `json:"scrollDepth"` + // Average engaged time per session in seconds, counting only foreground time. + // Sessions that reported no engagement are excluded. Only the flat aggregate + // computes it; null on breakdown and time-series rows. + EngagementTime *float64 `json:"engagementTime"` + + // Used by Decode() method + data []byte +} + +func (model AnalyticsMetric) New(data []byte) *AnalyticsMetric { + model.data = data + return &model +} + +func (model *AnalyticsMetric) Decode(value interface{}) error { + if len(model.data) <= 0 { + return errors.New("method Decode() cannot be used on nested struct") + } + + err := json.Unmarshal(model.data, value) + if err != nil { + return err + } + + return nil +} diff --git a/models/analyticsMetricList.go b/models/analyticsMetricList.go new file mode 100644 index 00000000..03e7fdae --- /dev/null +++ b/models/analyticsMetricList.go @@ -0,0 +1,36 @@ +package models + +import ( + "encoding/json" + "errors" +) + +// AnalyticsMetricList Model +type AnalyticsMetricList struct { + // Total number of metric rows returned. + Total int `json:"total"` + // Metric rows: one per time bucket, one per dimension value, or a single row + // for the flat aggregate. + Metrics []AnalyticsMetric `json:"metrics"` + + // Used by Decode() method + data []byte +} + +func (model AnalyticsMetricList) New(data []byte) *AnalyticsMetricList { + model.data = data + return &model +} + +func (model *AnalyticsMetricList) Decode(value interface{}) error { + if len(model.data) <= 0 { + return errors.New("method Decode() cannot be used on nested struct") + } + + err := json.Unmarshal(model.data, value) + if err != nil { + return err + } + + return nil +} diff --git a/models/analyticsMetricList_test.go b/models/analyticsMetricList_test.go new file mode 100644 index 00000000..fd4cc0f6 --- /dev/null +++ b/models/analyticsMetricList_test.go @@ -0,0 +1,24 @@ +package models + +import ( + "encoding/json" + "testing" +) + +func TestAnalyticsMetricListModel(t *testing.T) { + model := AnalyticsMetricList{Total: 30, Metrics: []AnalyticsMetric{AnalyticsMetric{Visitors: 1234, Sessions: 4567, Events: 8910}}} + + data, err := json.Marshal(model) + if err != nil { + t.Fatal(err) + } + + var result AnalyticsMetricList + err = json.Unmarshal(data, &result) + if err != nil { + t.Fatal(err) + } + if result.Total != model.Total { + t.Errorf("Expected Total %v, got %v", model.Total, result.Total) + } +} diff --git a/models/analyticsMetric_test.go b/models/analyticsMetric_test.go new file mode 100644 index 00000000..3de9d802 --- /dev/null +++ b/models/analyticsMetric_test.go @@ -0,0 +1,30 @@ +package models + +import ( + "encoding/json" + "testing" +) + +func TestAnalyticsMetricModel(t *testing.T) { + model := AnalyticsMetric{Visitors: 1234, Sessions: 4567, Events: 8910} + + data, err := json.Marshal(model) + if err != nil { + t.Fatal(err) + } + + var result AnalyticsMetric + err = json.Unmarshal(data, &result) + if err != nil { + t.Fatal(err) + } + if result.Visitors != model.Visitors { + t.Errorf("Expected Visitors %v, got %v", model.Visitors, result.Visitors) + } + if result.Sessions != model.Sessions { + t.Errorf("Expected Sessions %v, got %v", model.Sessions, result.Sessions) + } + if result.Events != model.Events { + t.Errorf("Expected Events %v, got %v", model.Events, result.Events) + } +} diff --git a/models/analyticsProperty.go b/models/analyticsProperty.go new file mode 100644 index 00000000..f4d53e50 --- /dev/null +++ b/models/analyticsProperty.go @@ -0,0 +1,52 @@ +package models + +import ( + "encoding/json" + "errors" +) + +// AnalyticsProperty Model +type AnalyticsProperty struct { + // Analytics property ID. + Id string `json:"$id"` + // Property creation date in ISO 8601 format. + CreatedAt string `json:"$createdAt"` + // Property update date in ISO 8601 format. + UpdatedAt string `json:"$updatedAt"` + // Human-readable name of the tracked website or application. + Name string `json:"name"` + // Primary domain being tracked (e.g. example.com). May be empty for native + // apps. + Domain string `json:"domain"` + // IANA timezone used to define the daily boundary for stats. + Timezone string `json:"timezone"` + // Whether tracking is currently active. + Enabled bool `json:"enabled"` + // Whether stats for this property are publicly viewable. + Public bool `json:"public"` + // List of origins allowed to send tracking events. Use ["*"] to allow all. + AllowedOrigins []string `json:"allowedOrigins"` + // Unique identifier for the tracking script snippet. + SnippetId string `json:"snippetId"` + + // Used by Decode() method + data []byte +} + +func (model AnalyticsProperty) New(data []byte) *AnalyticsProperty { + model.data = data + return &model +} + +func (model *AnalyticsProperty) Decode(value interface{}) error { + if len(model.data) <= 0 { + return errors.New("method Decode() cannot be used on nested struct") + } + + err := json.Unmarshal(model.data, value) + if err != nil { + return err + } + + return nil +} diff --git a/models/analyticsPropertyList.go b/models/analyticsPropertyList.go new file mode 100644 index 00000000..96577a71 --- /dev/null +++ b/models/analyticsPropertyList.go @@ -0,0 +1,35 @@ +package models + +import ( + "encoding/json" + "errors" +) + +// AnalyticsPropertiesList Model +type AnalyticsPropertyList struct { + // Total number of properties that matched your query. + Total int `json:"total"` + // List of properties. + Properties []AnalyticsProperty `json:"properties"` + + // Used by Decode() method + data []byte +} + +func (model AnalyticsPropertyList) New(data []byte) *AnalyticsPropertyList { + model.data = data + return &model +} + +func (model *AnalyticsPropertyList) Decode(value interface{}) error { + if len(model.data) <= 0 { + return errors.New("method Decode() cannot be used on nested struct") + } + + err := json.Unmarshal(model.data, value) + if err != nil { + return err + } + + return nil +} diff --git a/models/analyticsPropertyList_test.go b/models/analyticsPropertyList_test.go new file mode 100644 index 00000000..f3802458 --- /dev/null +++ b/models/analyticsPropertyList_test.go @@ -0,0 +1,24 @@ +package models + +import ( + "encoding/json" + "testing" +) + +func TestAnalyticsPropertyListModel(t *testing.T) { + model := AnalyticsPropertyList{Total: 5, Properties: []AnalyticsProperty{AnalyticsProperty{Id: "5e5ea5c16897e", CreatedAt: "2020-10-15T06:38:00.000+00:00", UpdatedAt: "2020-10-15T06:38:00.000+00:00", Name: "My Website", Domain: "example.com", Timezone: "UTC", Enabled: true, Public: true, AllowedOrigins: []string{"test"}, SnippetId: "snp_a1b2c3d4e5"}}} + + data, err := json.Marshal(model) + if err != nil { + t.Fatal(err) + } + + var result AnalyticsPropertyList + err = json.Unmarshal(data, &result) + if err != nil { + t.Fatal(err) + } + if result.Total != model.Total { + t.Errorf("Expected Total %v, got %v", model.Total, result.Total) + } +} diff --git a/models/analyticsProperty_test.go b/models/analyticsProperty_test.go new file mode 100644 index 00000000..76ab8216 --- /dev/null +++ b/models/analyticsProperty_test.go @@ -0,0 +1,48 @@ +package models + +import ( + "encoding/json" + "testing" +) + +func TestAnalyticsPropertyModel(t *testing.T) { + model := AnalyticsProperty{Id: "5e5ea5c16897e", CreatedAt: "2020-10-15T06:38:00.000+00:00", UpdatedAt: "2020-10-15T06:38:00.000+00:00", Name: "My Website", Domain: "example.com", Timezone: "UTC", Enabled: true, Public: true, AllowedOrigins: []string{"test"}, SnippetId: "snp_a1b2c3d4e5"} + + data, err := json.Marshal(model) + if err != nil { + t.Fatal(err) + } + + var result AnalyticsProperty + err = json.Unmarshal(data, &result) + if err != nil { + t.Fatal(err) + } + if result.Id != model.Id { + t.Errorf("Expected Id %v, got %v", model.Id, result.Id) + } + if result.CreatedAt != model.CreatedAt { + t.Errorf("Expected CreatedAt %v, got %v", model.CreatedAt, result.CreatedAt) + } + if result.UpdatedAt != model.UpdatedAt { + t.Errorf("Expected UpdatedAt %v, got %v", model.UpdatedAt, result.UpdatedAt) + } + if result.Name != model.Name { + t.Errorf("Expected Name %v, got %v", model.Name, result.Name) + } + if result.Domain != model.Domain { + t.Errorf("Expected Domain %v, got %v", model.Domain, result.Domain) + } + if result.Timezone != model.Timezone { + t.Errorf("Expected Timezone %v, got %v", model.Timezone, result.Timezone) + } + if result.Enabled != model.Enabled { + t.Errorf("Expected Enabled %v, got %v", model.Enabled, result.Enabled) + } + if result.Public != model.Public { + t.Errorf("Expected Public %v, got %v", model.Public, result.Public) + } + if result.SnippetId != model.SnippetId { + t.Errorf("Expected SnippetId %v, got %v", model.SnippetId, result.SnippetId) + } +} diff --git a/models/backupArchive.go b/models/backupArchive.go index 39988c77..d11f1954 100644 --- a/models/backupArchive.go +++ b/models/backupArchive.go @@ -15,13 +15,13 @@ type BackupArchive struct { UpdatedAt string `json:"$updatedAt"` // Archive policy ID. PolicyId string `json:"policyId"` - // Archive size in bytes. - Size int `json:"size"` + // Archive size in bytes. Null until the size is known. + Size *int `json:"size"` // The status of the archive creation. Possible values: pending, processing, // uploading, completed, failed, skipped. Status string `json:"status"` - // The backup start time. - StartedAt string `json:"startedAt"` + // The backup start time. Null until the backup starts. + StartedAt *string `json:"startedAt"` // Migration ID. MigrationId string `json:"migrationId"` // The services that are backed up by this archive. diff --git a/models/backupArchiveList_test.go b/models/backupArchiveList_test.go index 0fe792a6..619867ba 100644 --- a/models/backupArchiveList_test.go +++ b/models/backupArchiveList_test.go @@ -6,7 +6,7 @@ import ( ) func TestBackupArchiveListModel(t *testing.T) { - model := BackupArchiveList{Total: 5, Archives: []BackupArchive{BackupArchive{Id: "5e5ea5c16897e", CreatedAt: "2020-10-15T06:38:00.000+00:00", UpdatedAt: "2020-10-15T06:38:00.000+00:00", PolicyId: "did8jx6ws45jana098ab7", Size: 100000, Status: "completed", StartedAt: "2020-10-15T06:38:00.000+00:00", MigrationId: "did8jx6ws45jana098ab7", Services: []string{"test"}, Resources: []string{"test"}}}} + model := BackupArchiveList{Total: 5, Archives: []BackupArchive{BackupArchive{Id: "5e5ea5c16897e", CreatedAt: "2020-10-15T06:38:00.000+00:00", UpdatedAt: "2020-10-15T06:38:00.000+00:00", PolicyId: "did8jx6ws45jana098ab7", Status: "completed", MigrationId: "did8jx6ws45jana098ab7", Services: []string{"test"}, Resources: []string{"test"}}}} data, err := json.Marshal(model) if err != nil { diff --git a/models/backupArchive_test.go b/models/backupArchive_test.go index 10ee6128..44cf16ac 100644 --- a/models/backupArchive_test.go +++ b/models/backupArchive_test.go @@ -6,7 +6,7 @@ import ( ) func TestBackupArchiveModel(t *testing.T) { - model := BackupArchive{Id: "5e5ea5c16897e", CreatedAt: "2020-10-15T06:38:00.000+00:00", UpdatedAt: "2020-10-15T06:38:00.000+00:00", PolicyId: "did8jx6ws45jana098ab7", Size: 100000, Status: "completed", StartedAt: "2020-10-15T06:38:00.000+00:00", MigrationId: "did8jx6ws45jana098ab7", Services: []string{"test"}, Resources: []string{"test"}} + model := BackupArchive{Id: "5e5ea5c16897e", CreatedAt: "2020-10-15T06:38:00.000+00:00", UpdatedAt: "2020-10-15T06:38:00.000+00:00", PolicyId: "did8jx6ws45jana098ab7", Status: "completed", MigrationId: "did8jx6ws45jana098ab7", Services: []string{"test"}, Resources: []string{"test"}} data, err := json.Marshal(model) if err != nil { @@ -30,15 +30,9 @@ func TestBackupArchiveModel(t *testing.T) { if result.PolicyId != model.PolicyId { t.Errorf("Expected PolicyId %v, got %v", model.PolicyId, result.PolicyId) } - if result.Size != model.Size { - t.Errorf("Expected Size %v, got %v", model.Size, result.Size) - } if result.Status != model.Status { t.Errorf("Expected Status %v, got %v", model.Status, result.Status) } - if result.StartedAt != model.StartedAt { - t.Errorf("Expected StartedAt %v, got %v", model.StartedAt, result.StartedAt) - } if result.MigrationId != model.MigrationId { t.Errorf("Expected MigrationId %v, got %v", model.MigrationId, result.MigrationId) } diff --git a/models/backupRestoration.go b/models/backupRestoration.go index 582dff9b..b7034646 100644 --- a/models/backupRestoration.go +++ b/models/backupRestoration.go @@ -20,16 +20,16 @@ type BackupRestoration struct { // The status of the restoration. Possible values: pending, downloading, // processing, completed, failed. Status string `json:"status"` - // The backup start time. - StartedAt string `json:"startedAt"` + // The restoration start time. Null until the restoration starts. + StartedAt *string `json:"startedAt"` // Migration ID. MigrationId string `json:"migrationId"` // The services that are backed up by this policy. Services []string `json:"services"` // The resources that are backed up by this policy. Resources []string `json:"resources"` - // Optional data in key-value object. - Options string `json:"options"` + // Restoration options as a key-value object. + Options interface{} `json:"options"` // Used by Decode() method data []byte diff --git a/models/backupRestorationList_test.go b/models/backupRestorationList_test.go index 5e0d9c42..bb683f5c 100644 --- a/models/backupRestorationList_test.go +++ b/models/backupRestorationList_test.go @@ -6,7 +6,7 @@ import ( ) func TestBackupRestorationListModel(t *testing.T) { - model := BackupRestorationList{Total: 5, Restorations: []BackupRestoration{BackupRestoration{Id: "5e5ea5c16897e", CreatedAt: "2020-10-15T06:38:00.000+00:00", UpdatedAt: "2020-10-15T06:38:00.000+00:00", ArchiveId: "did8jx6ws45jana098ab7", PolicyId: "did8jx6ws45jana098ab7", Status: "completed", StartedAt: "2020-10-15T06:38:00.000+00:00", MigrationId: "did8jx6ws45jana098ab7", Services: []string{"test"}, Resources: []string{"test"}, Options: "{databases.database[{oldId, newId, newName}]}"}}} + model := BackupRestorationList{Total: 5, Restorations: []BackupRestoration{BackupRestoration{Id: "5e5ea5c16897e", CreatedAt: "2020-10-15T06:38:00.000+00:00", UpdatedAt: "2020-10-15T06:38:00.000+00:00", ArchiveId: "did8jx6ws45jana098ab7", PolicyId: "did8jx6ws45jana098ab7", Status: "completed", MigrationId: "did8jx6ws45jana098ab7", Services: []string{"test"}, Resources: []string{"test"}, Options: map[string]interface{}{}}}} data, err := json.Marshal(model) if err != nil { diff --git a/models/backupRestoration_test.go b/models/backupRestoration_test.go index a81ad852..e1c3f88e 100644 --- a/models/backupRestoration_test.go +++ b/models/backupRestoration_test.go @@ -6,7 +6,7 @@ import ( ) func TestBackupRestorationModel(t *testing.T) { - model := BackupRestoration{Id: "5e5ea5c16897e", CreatedAt: "2020-10-15T06:38:00.000+00:00", UpdatedAt: "2020-10-15T06:38:00.000+00:00", ArchiveId: "did8jx6ws45jana098ab7", PolicyId: "did8jx6ws45jana098ab7", Status: "completed", StartedAt: "2020-10-15T06:38:00.000+00:00", MigrationId: "did8jx6ws45jana098ab7", Services: []string{"test"}, Resources: []string{"test"}, Options: "{databases.database[{oldId, newId, newName}]}"} + model := BackupRestoration{Id: "5e5ea5c16897e", CreatedAt: "2020-10-15T06:38:00.000+00:00", UpdatedAt: "2020-10-15T06:38:00.000+00:00", ArchiveId: "did8jx6ws45jana098ab7", PolicyId: "did8jx6ws45jana098ab7", Status: "completed", MigrationId: "did8jx6ws45jana098ab7", Services: []string{"test"}, Resources: []string{"test"}, Options: map[string]interface{}{}} data, err := json.Marshal(model) if err != nil { @@ -36,13 +36,7 @@ func TestBackupRestorationModel(t *testing.T) { if result.Status != model.Status { t.Errorf("Expected Status %v, got %v", model.Status, result.Status) } - if result.StartedAt != model.StartedAt { - t.Errorf("Expected StartedAt %v, got %v", model.StartedAt, result.StartedAt) - } if result.MigrationId != model.MigrationId { t.Errorf("Expected MigrationId %v, got %v", model.MigrationId, result.MigrationId) } - if result.Options != model.Options { - t.Errorf("Expected Options %v, got %v", model.Options, result.Options) - } } diff --git a/models/billingPlan.go b/models/billingPlan.go index d8edc4ad..7faaa08e 100644 --- a/models/billingPlan.go +++ b/models/billingPlan.go @@ -90,7 +90,7 @@ type BillingPlan struct { ProjectInactivityDays int `json:"projectInactivityDays"` // Alert threshold percentage AlertLimit int `json:"alertLimit"` - // Additional resources + // Additional resources. Null when the plan does not support usage billing. Usage UsageBillingPlan `json:"usage"` // Addons Addons BillingPlanAddon `json:"addons"` diff --git a/models/billingPlan_test.go b/models/billingPlan_test.go index 0be15643..5aba812a 100644 --- a/models/billingPlan_test.go +++ b/models/billingPlan_test.go @@ -6,7 +6,7 @@ import ( ) func TestBillingPlanModel(t *testing.T) { - model := BillingPlan{Id: "tier-0", Name: "Hobby", Desc: "Hobby plan", Order: 0, Price: 25, Trial: 14, Bandwidth: 25, Storage: 25, ImageTransformations: 100, ScreenshotsGenerated: 50, Webhooks: 25, WafRules: 2, Projects: 2, Platforms: 3, Users: 25, Teams: 25, Databases: 25, DatabasesReads: 500000, DatabasesWrites: 250000, DatabasesBatchSize: 100, Buckets: 25, FileSize: 25, Functions: 25, Sites: 1, Executions: 25, ExecutionsRetentionCount: 10000, GBHours: 100, Realtime: 25, RealtimeMessages: 100000, Messages: 1000, Topics: 1, AuthPhone: 10, Domains: 5, UsageLogs: 30, ProjectInactivityDays: 7, AlertLimit: 80, Usage: UsageBillingPlan{Bandwidth: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}, Executions: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}, Realtime: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}, RealtimeMessages: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}, Storage: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}, Users: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}, GBHours: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}, ImageTransformations: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}}, Addons: BillingPlanAddon{}, BudgetCapEnabled: true, CustomSmtp: true, EmailBranding: true, RequiresPaymentMethod: true, RequiresBillingAddress: true, IsAvailable: true, SelfService: true, PremiumSupport: true, Budgeting: true, SupportsMockNumbers: true, SupportsOrganizationRoles: true, SupportsCredits: true, SupportsDedicatedDatabases: true, SupportsDisposableEmailValidation: true, SupportsCanonicalEmailValidation: true, SupportsFreeEmailValidation: true, SupportsCorporateEmailValidation: true, SupportsProjectSpecificRoles: true, UsagePerProject: true, SupportedAddons: BillingPlanSupportedAddons{Baa: true, PremiumGeoDB: true, PremiumGeoDBOrg: true}, DeploymentSize: 30, BuildSize: 2000, DatabasesAllowEncrypt: true, Group: "pro", DatabaseComputeCredit: 10} + model := BillingPlan{Id: "tier-0", Name: "Hobby", Desc: "Hobby plan", Order: 0, Price: 25, Trial: 14, Bandwidth: 25, Storage: 25, ImageTransformations: 100, ScreenshotsGenerated: 50, Webhooks: 25, WafRules: 2, Projects: 2, Platforms: 3, Users: 25, Teams: 25, Databases: 25, DatabasesReads: 500000, DatabasesWrites: 250000, DatabasesBatchSize: 100, Buckets: 25, FileSize: 25, Functions: 25, Sites: 1, Executions: 25, ExecutionsRetentionCount: 10000, GBHours: 100, Realtime: 25, RealtimeMessages: 100000, Messages: 1000, Topics: 1, AuthPhone: 10, Domains: 5, UsageLogs: 30, ProjectInactivityDays: 7, AlertLimit: 80, Addons: BillingPlanAddon{}, BudgetCapEnabled: true, CustomSmtp: true, EmailBranding: true, RequiresPaymentMethod: true, RequiresBillingAddress: true, IsAvailable: true, SelfService: true, PremiumSupport: true, Budgeting: true, SupportsMockNumbers: true, SupportsOrganizationRoles: true, SupportsCredits: true, SupportsDedicatedDatabases: true, SupportsDisposableEmailValidation: true, SupportsCanonicalEmailValidation: true, SupportsFreeEmailValidation: true, SupportsCorporateEmailValidation: true, SupportsProjectSpecificRoles: true, UsagePerProject: true, SupportedAddons: BillingPlanSupportedAddons{Baa: true, PremiumGeoDB: true, PremiumGeoDBOrg: true}, DeploymentSize: 30, BuildSize: 2000, DatabasesAllowEncrypt: true, Group: "pro", DatabaseComputeCredit: 10} data, err := json.Marshal(model) if err != nil { diff --git a/models/databaseStatus.go b/models/databaseStatus.go index cee1549e..3188f29d 100644 --- a/models/databaseStatus.go +++ b/models/databaseStatus.go @@ -18,7 +18,7 @@ type DatabaseStatus struct { Version string `json:"version"` // Database uptime in seconds. Uptime int `json:"uptime"` - // Connection statistics. + // Connection statistics. Null when the database has not been probed. Connections DatabaseStatusConnections `json:"connections"` // Requested replication sync mode. Possible values: async, sync, quorum. // Compare with effectiveSyncMode for what the primary is enforcing. diff --git a/models/databaseStatus_test.go b/models/databaseStatus_test.go index afd35781..bd6012b5 100644 --- a/models/databaseStatus_test.go +++ b/models/databaseStatus_test.go @@ -6,7 +6,7 @@ import ( ) func TestDatabaseStatusModel(t *testing.T) { - model := DatabaseStatus{Health: "healthy", Ready: true, Engine: "postgresql", Version: "17", Uptime: 86400, Connections: DatabaseStatusConnections{Current: 12, Max: 100}, SyncMode: "async", SyncDegraded: true, SyncAcknowledgements: 1, SyncStandbyCount: 2, Replicas: []DatabaseStatusReplica{DatabaseStatusReplica{Index: 0, Role: "primary", Healthy: true}}, Volumes: []DatabaseStatusVolume{DatabaseStatusVolume{Path: "/var/lib/postgresql/data", UsedPercent: "45%", Available: "55GB", Mounted: true}}} + model := DatabaseStatus{Health: "healthy", Ready: true, Engine: "postgresql", Version: "17", Uptime: 86400, SyncMode: "async", SyncDegraded: true, SyncAcknowledgements: 1, SyncStandbyCount: 2, Replicas: []DatabaseStatusReplica{DatabaseStatusReplica{Index: 0, Role: "primary", Healthy: true}}, Volumes: []DatabaseStatusVolume{DatabaseStatusVolume{Path: "/var/lib/postgresql/data", UsedPercent: "45%", Available: "55GB", Mounted: true}}} data, err := json.Marshal(model) if err != nil { diff --git a/models/oAuth2Webflow.go b/models/oAuth2Webflow.go new file mode 100644 index 00000000..f931c803 --- /dev/null +++ b/models/oAuth2Webflow.go @@ -0,0 +1,39 @@ +package models + +import ( + "encoding/json" + "errors" +) + +// OAuth2Webflow Model +type OAuth2Webflow struct { + // OAuth2 provider ID. + Id string `json:"$id"` + // OAuth2 provider is active and can be used to create sessions. + Enabled bool `json:"enabled"` + // Webflow OAuth2 client ID. + ClientId string `json:"clientId"` + // Webflow OAuth2 client secret. + ClientSecret string `json:"clientSecret"` + + // Used by Decode() method + data []byte +} + +func (model OAuth2Webflow) New(data []byte) *OAuth2Webflow { + model.data = data + return &model +} + +func (model *OAuth2Webflow) Decode(value interface{}) error { + if len(model.data) <= 0 { + return errors.New("method Decode() cannot be used on nested struct") + } + + err := json.Unmarshal(model.data, value) + if err != nil { + return err + } + + return nil +} diff --git a/models/oAuth2Webflow_test.go b/models/oAuth2Webflow_test.go new file mode 100644 index 00000000..49ef4df2 --- /dev/null +++ b/models/oAuth2Webflow_test.go @@ -0,0 +1,33 @@ +package models + +import ( + "encoding/json" + "testing" +) + +func TestOAuth2WebflowModel(t *testing.T) { + model := OAuth2Webflow{Id: "github", Enabled: true, ClientId: "8bb20000000000000000000000000000000000000000000000000000000040dd", ClientSecret: "59bf00000000000000000000000000000000000000000000000000000000fe59"} + + data, err := json.Marshal(model) + if err != nil { + t.Fatal(err) + } + + var result OAuth2Webflow + err = json.Unmarshal(data, &result) + if err != nil { + t.Fatal(err) + } + if result.Id != model.Id { + t.Errorf("Expected Id %v, got %v", model.Id, result.Id) + } + if result.Enabled != model.Enabled { + t.Errorf("Expected Enabled %v, got %v", model.Enabled, result.Enabled) + } + if result.ClientId != model.ClientId { + t.Errorf("Expected ClientId %v, got %v", model.ClientId, result.ClientId) + } + if result.ClientSecret != model.ClientSecret { + t.Errorf("Expected ClientSecret %v, got %v", model.ClientSecret, result.ClientSecret) + } +} diff --git a/models/organization_test.go b/models/organization_test.go index 57744ac3..183a2a12 100644 --- a/models/organization_test.go +++ b/models/organization_test.go @@ -6,7 +6,7 @@ import ( ) func TestOrganizationModel(t *testing.T) { - model := Organization{Id: "5e5ea5c16897e", CreatedAt: "2020-10-15T06:38:00.000+00:00", UpdatedAt: "2020-10-15T06:38:00.000+00:00", Name: "VIP", Total: 7, Prefs: Preferences{}, BudgetAlerts: []int{1}, BillingPlan: "tier-1", BillingPlanId: "tier-1", BillingPlanDetails: BillingPlan{Id: "tier-0", Name: "Hobby", Desc: "Hobby plan", Order: 0, Price: 25, Trial: 14, Bandwidth: 25, Storage: 25, ImageTransformations: 100, ScreenshotsGenerated: 50, Webhooks: 25, WafRules: 2, Projects: 2, Platforms: 3, Users: 25, Teams: 25, Databases: 25, DatabasesReads: 500000, DatabasesWrites: 250000, DatabasesBatchSize: 100, Buckets: 25, FileSize: 25, Functions: 25, Sites: 1, Executions: 25, ExecutionsRetentionCount: 10000, GBHours: 100, Realtime: 25, RealtimeMessages: 100000, Messages: 1000, Topics: 1, AuthPhone: 10, Domains: 5, UsageLogs: 30, ProjectInactivityDays: 7, AlertLimit: 80, Usage: UsageBillingPlan{Bandwidth: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}, Executions: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}, Realtime: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}, RealtimeMessages: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}, Storage: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}, Users: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}, GBHours: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}, ImageTransformations: AdditionalResource{Name: "string", Unit: "GB", Currency: "USD", Price: 5, Value: 25, InvoiceDesc: "string"}}, Addons: BillingPlanAddon{}, BudgetCapEnabled: true, CustomSmtp: true, EmailBranding: true, RequiresPaymentMethod: true, RequiresBillingAddress: true, IsAvailable: true, SelfService: true, PremiumSupport: true, Budgeting: true, SupportsMockNumbers: true, SupportsOrganizationRoles: true, SupportsCredits: true, SupportsDedicatedDatabases: true, SupportsDisposableEmailValidation: true, SupportsCanonicalEmailValidation: true, SupportsFreeEmailValidation: true, SupportsCorporateEmailValidation: true, SupportsProjectSpecificRoles: true, UsagePerProject: true, SupportedAddons: BillingPlanSupportedAddons{Baa: true, PremiumGeoDB: true, PremiumGeoDBOrg: true}, DeploymentSize: 30, BuildSize: 2000, DatabasesAllowEncrypt: true, Group: "pro", DatabaseComputeCredit: 10}, BillingEmail: "billing@org.example", BillingStartDate: "2020-10-15T06:38:00.000+00:00", BillingCurrentInvoiceDate: "2020-10-15T06:38:00.000+00:00", BillingNextInvoiceDate: "2020-10-15T06:38:00.000+00:00", BillingTrialDays: 14, BillingAggregationId: "adbc3de4rddfsd", BillingInvoiceId: "adbc3de4rddfsd", PaymentMethodId: "adbc3de4rddfsd", Status: "active", MarkedForDeletion: true, Platform: "imagine", Projects: []string{"test"}} + model := Organization{Id: "5e5ea5c16897e", CreatedAt: "2020-10-15T06:38:00.000+00:00", UpdatedAt: "2020-10-15T06:38:00.000+00:00", Name: "VIP", Total: 7, Prefs: Preferences{}, BudgetAlerts: []int{1}, BillingPlan: "tier-1", BillingPlanId: "tier-1", BillingPlanDetails: BillingPlan{Id: "tier-0", Name: "Hobby", Desc: "Hobby plan", Order: 0, Price: 25, Trial: 14, Bandwidth: 25, Storage: 25, ImageTransformations: 100, ScreenshotsGenerated: 50, Webhooks: 25, WafRules: 2, Projects: 2, Platforms: 3, Users: 25, Teams: 25, Databases: 25, DatabasesReads: 500000, DatabasesWrites: 250000, DatabasesBatchSize: 100, Buckets: 25, FileSize: 25, Functions: 25, Sites: 1, Executions: 25, ExecutionsRetentionCount: 10000, GBHours: 100, Realtime: 25, RealtimeMessages: 100000, Messages: 1000, Topics: 1, AuthPhone: 10, Domains: 5, UsageLogs: 30, ProjectInactivityDays: 7, AlertLimit: 80, Addons: BillingPlanAddon{}, BudgetCapEnabled: true, CustomSmtp: true, EmailBranding: true, RequiresPaymentMethod: true, RequiresBillingAddress: true, IsAvailable: true, SelfService: true, PremiumSupport: true, Budgeting: true, SupportsMockNumbers: true, SupportsOrganizationRoles: true, SupportsCredits: true, SupportsDedicatedDatabases: true, SupportsDisposableEmailValidation: true, SupportsCanonicalEmailValidation: true, SupportsFreeEmailValidation: true, SupportsCorporateEmailValidation: true, SupportsProjectSpecificRoles: true, UsagePerProject: true, SupportedAddons: BillingPlanSupportedAddons{Baa: true, PremiumGeoDB: true, PremiumGeoDBOrg: true}, DeploymentSize: 30, BuildSize: 2000, DatabasesAllowEncrypt: true, Group: "pro", DatabaseComputeCredit: 10}, BillingEmail: "billing@org.example", BillingStartDate: "2020-10-15T06:38:00.000+00:00", BillingCurrentInvoiceDate: "2020-10-15T06:38:00.000+00:00", BillingNextInvoiceDate: "2020-10-15T06:38:00.000+00:00", BillingTrialDays: 14, BillingAggregationId: "adbc3de4rddfsd", BillingInvoiceId: "adbc3de4rddfsd", PaymentMethodId: "adbc3de4rddfsd", Status: "active", MarkedForDeletion: true, Platform: "imagine", Projects: []string{"test"}} data, err := json.Marshal(model) if err != nil { diff --git a/models/proxyRule.go b/models/proxyRule.go index b0aa0709..eef8fd85 100644 --- a/models/proxyRule.go +++ b/models/proxyRule.go @@ -27,8 +27,7 @@ type ProxyRule struct { RedirectStatusCode int `json:"redirectStatusCode"` // ID of deployment. Used if type is "deployment" DeploymentId string `json:"deploymentId"` - // Type of deployment. Possible values are "function", "site". Used if rule's - // type is "deployment". + // Type of deployment resource: function, site, or dedicatedDatabase. DeploymentResourceType *string `json:"deploymentResourceType"` // ID of deployment's resource (site or function ID). Used if type is // "deployment" diff --git a/models/webhook.go b/models/webhook.go index ec7710eb..993ff232 100644 --- a/models/webhook.go +++ b/models/webhook.go @@ -23,7 +23,7 @@ type Webhook struct { Tls bool `json:"tls"` // HTTP basic authentication username. AuthUsername string `json:"authUsername"` - // HTTP basic authentication password. + // HTTP basic authentication password. Write-only: always returned empty. AuthPassword string `json:"authPassword"` // Signature key which can be used to validate incoming webhook payloads. Only // returned on creation and secret rotation. diff --git a/mongo/mongo_test.go b/mongo/mongo_test.go index eedc05f8..c4cbadaf 100644 --- a/mongo/mongo_test.go +++ b/mongo/mongo_test.go @@ -534,7 +534,7 @@ func TestMongo(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.CreateBackupPolicy("<DATABASE_ID>", "<POLICY_ID>", "<NAME>", "", 1) + _, err := srv.CreateBackupPolicy("<DATABASE_ID>", "<POLICY_ID>", "<NAME>", "schedule", 1) if err != nil { t.Errorf("Method CreateBackupPolicy failed: %v", err) } @@ -1400,10 +1400,6 @@ func TestMongo(t *testing.T) { "engine": "postgresql", "version": "17", "uptime": 86400, - "connections": { - "current": 12, - "max": 100 - }, "syncMode": "async", "syncDegraded": true, "syncAcknowledgements": 1, diff --git a/mysql/mysql_test.go b/mysql/mysql_test.go index 3df3722a..a8cd671a 100644 --- a/mysql/mysql_test.go +++ b/mysql/mysql_test.go @@ -534,7 +534,7 @@ func TestMysql(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.CreateBackupPolicy("<DATABASE_ID>", "<POLICY_ID>", "<NAME>", "", 1) + _, err := srv.CreateBackupPolicy("<DATABASE_ID>", "<POLICY_ID>", "<NAME>", "schedule", 1) if err != nil { t.Errorf("Method CreateBackupPolicy failed: %v", err) } @@ -1506,10 +1506,6 @@ func TestMysql(t *testing.T) { "engine": "postgresql", "version": "17", "uptime": 86400, - "connections": { - "current": 12, - "max": 100 - }, "syncMode": "async", "syncDegraded": true, "syncAcknowledgements": 1, diff --git a/organization/organization_test.go b/organization/organization_test.go index c77b489c..8742c95e 100644 --- a/organization/organization_test.go +++ b/organization/organization_test.go @@ -66,72 +66,6 @@ func TestOrganization(t *testing.T) { "usageLogs": 30, "projectInactivityDays": 7, "alertLimit": 80, - "usage": { - "bandwidth": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - }, - "executions": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - }, - "realtime": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - }, - "realtimeMessages": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - }, - "storage": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - }, - "users": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - }, - "GBHours": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - }, - "imageTransformations": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - } - }, "addons": { }, "budgetCapEnabled": true, @@ -248,72 +182,6 @@ func TestOrganization(t *testing.T) { "usageLogs": 30, "projectInactivityDays": 7, "alertLimit": 80, - "usage": { - "bandwidth": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - }, - "executions": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - }, - "realtime": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - }, - "realtimeMessages": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - }, - "storage": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - }, - "users": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - }, - "GBHours": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - }, - "imageTransformations": { - "name": "string", - "unit": "GB", - "currency": "USD", - "price": 5, - "value": 25, - "invoiceDesc": "string" - } - }, "addons": { }, "budgetCapEnabled": true, diff --git a/postgresql/postgresql_test.go b/postgresql/postgresql_test.go index ab7980fd..2072d994 100644 --- a/postgresql/postgresql_test.go +++ b/postgresql/postgresql_test.go @@ -534,7 +534,7 @@ func TestPostgresql(t *testing.T) { srv := New(newTestClient(ts)) - _, err := srv.CreateBackupPolicy("<DATABASE_ID>", "<POLICY_ID>", "<NAME>", "", 1) + _, err := srv.CreateBackupPolicy("<DATABASE_ID>", "<POLICY_ID>", "<NAME>", "schedule", 1) if err != nil { t.Errorf("Method CreateBackupPolicy failed: %v", err) } @@ -1689,10 +1689,6 @@ func TestPostgresql(t *testing.T) { "engine": "postgresql", "version": "17", "uptime": 86400, - "connections": { - "current": 12, - "max": 100 - }, "syncMode": "async", "syncDegraded": true, "syncAcknowledgements": 1, diff --git a/project/project.go b/project/project.go index 024ab9d6..2d905f2d 100644 --- a/project/project.go +++ b/project/project.go @@ -4732,6 +4732,89 @@ func (srv *Project) UpdateOAuth2Twitch(optionalSetters ...UpdateOAuth2TwitchOpti } +type UpdateOAuth2WebflowOptions struct { + ClientId string + ClientSecret string + Enabled bool + enabledSetters map[string]bool +} + +func (options UpdateOAuth2WebflowOptions) New() *UpdateOAuth2WebflowOptions { + options.enabledSetters = map[string]bool{"ClientId": false, "ClientSecret": false, "Enabled": false} + return &options +} + +type UpdateOAuth2WebflowOption func(*UpdateOAuth2WebflowOptions) + +func (srv *Project) WithUpdateOAuth2WebflowClientId(v string) UpdateOAuth2WebflowOption { + return func(o *UpdateOAuth2WebflowOptions) { + o.ClientId = v + o.enabledSetters["ClientId"] = true + } +} +func (srv *Project) WithUpdateOAuth2WebflowClientSecret(v string) UpdateOAuth2WebflowOption { + return func(o *UpdateOAuth2WebflowOptions) { + o.ClientSecret = v + o.enabledSetters["ClientSecret"] = true + } +} +func (srv *Project) WithUpdateOAuth2WebflowEnabled(v bool) UpdateOAuth2WebflowOption { + return func(o *UpdateOAuth2WebflowOptions) { + o.Enabled = v + o.enabledSetters["Enabled"] = true + } +} + +// UpdateOAuth2Webflow update the project OAuth2 Webflow configuration. +func (srv *Project) UpdateOAuth2Webflow(optionalSetters ...UpdateOAuth2WebflowOption) (*models.OAuth2Webflow, error) { + path := "/project/oauth2/webflow" + options := UpdateOAuth2WebflowOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } + params := map[string]interface{}{} + if options.enabledSetters["ClientId"] { + params["clientId"] = options.ClientId + } + if options.enabledSetters["ClientSecret"] { + params["clientSecret"] = options.ClientSecret + } + if options.enabledSetters["Enabled"] { + params["enabled"] = options.Enabled + } + headers := map[string]interface{}{} + headers["X-Appwrite-Project"] = srv.client.Config["project"] + headers["content-type"] = "application/json" + headers["accept"] = "application/json" + + resp, err := srv.client.Call("PATCH", path, headers, params) + if err != nil { + return nil, err + } + if strings.HasPrefix(resp.Type, "application/json") { + bytes, err := client.ResponseBody(resp) + if err != nil { + return nil, err + } + + parsed := models.OAuth2Webflow{}.New(bytes) + + err = json.Unmarshal(bytes, parsed) + if err != nil { + return nil, err + } + + return parsed, nil + } + var parsed models.OAuth2Webflow + parsed, ok := resp.Result.(models.OAuth2Webflow) + if !ok { + return nil, errors.New("unexpected response type") + } + return &parsed, nil + +} + type UpdateOAuth2WordPressOptions struct { ClientId string ClientSecret string @@ -5385,6 +5468,14 @@ func (srv *Project) GetOAuth2Provider(ProviderId string) (models.Model, error) { return parsed, nil } + if fmt.Sprint(response["$id"]) == "webflow" { + parsed := models.OAuth2Webflow{}.New(bytes) + if err := json.Unmarshal(bytes, parsed); err != nil { + return nil, err + } + + return parsed, nil + } if fmt.Sprint(response["$id"]) == "twitch" { parsed := models.OAuth2Twitch{}.New(bytes) if err := json.Unmarshal(bytes, parsed); err != nil { diff --git a/project/project_test.go b/project/project_test.go index ac274d90..c192be5d 100644 --- a/project/project_test.go +++ b/project/project_test.go @@ -1922,6 +1922,35 @@ func TestProject(t *testing.T) { } }) + t.Run("Test UpdateOAuth2Webflow", func(t *testing.T) { + mockResponse := ` +{ + "$id": "github", + "enabled": true, + "clientId": "8bb20000000000000000000000000000000000000000000000000000000040dd", + "clientSecret": "59bf00000000000000000000000000000000000000000000000000000000fe59" +} +` + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "PATCH" { + t.Errorf("Expected method PATCH, got %s", r.Method) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(mockResponse)) + })) + defer ts.Close() + + srv := New(newTestClient(ts)) + + _, err := srv.UpdateOAuth2Webflow() + if err != nil { + t.Errorf("Method UpdateOAuth2Webflow failed: %v", err) + } + }) + t.Run("Test UpdateOAuth2WordPress", func(t *testing.T) { mockResponse := ` { diff --git a/proxy/proxy.go b/proxy/proxy.go index 57beb5c9..773c96df 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -44,6 +44,8 @@ func (srv *Proxy) WithCreateInvalidationReference(v string) CreateInvalidationOp // // Depending on type, the invalidation purges a single cache tag, a single URL // path, or all cached content for the domain. +// +// Domains that route to a function do not support cache invalidation. func (srv *Proxy) CreateInvalidation(Domain string, Type string, optionalSetters ...CreateInvalidationOption) (*models.ProxyInvalidation, error) { path := "/proxy/invalidations" options := CreateInvalidationOptions{}.New() diff --git a/sites/sites.go b/sites/sites.go index 60158fad..46ca0378 100644 --- a/sites/sites.go +++ b/sites/sites.go @@ -362,11 +362,37 @@ func (srv *Sites) Create(SiteId string, Name string, Framework string, BuildRunt } +type ListFrameworksOptions struct { + Total bool + enabledSetters map[string]bool +} + +func (options ListFrameworksOptions) New() *ListFrameworksOptions { + options.enabledSetters = map[string]bool{"Total": false} + return &options +} + +type ListFrameworksOption func(*ListFrameworksOptions) + +func (srv *Sites) WithListFrameworksTotal(v bool) ListFrameworksOption { + return func(o *ListFrameworksOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} + // ListFrameworks get a list of all frameworks that are currently available on // the server instance. -func (srv *Sites) ListFrameworks() (*models.FrameworkList, error) { +func (srv *Sites) ListFrameworks(optionalSetters ...ListFrameworksOption) (*models.FrameworkList, error) { path := "/sites/frameworks" + options := ListFrameworksOptions{}.New() + for _, opt := range optionalSetters { + opt(options) + } params := map[string]interface{}{} + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" @@ -401,11 +427,12 @@ func (srv *Sites) ListFrameworks() (*models.FrameworkList, error) { type ListSpecificationsOptions struct { Type string + Total bool enabledSetters map[string]bool } func (options ListSpecificationsOptions) New() *ListSpecificationsOptions { - options.enabledSetters = map[string]bool{"Type": false} + options.enabledSetters = map[string]bool{"Type": false, "Total": false} return &options } @@ -417,6 +444,12 @@ func (srv *Sites) WithListSpecificationsType(v string) ListSpecificationsOption o.enabledSetters["Type"] = true } } +func (srv *Sites) WithListSpecificationsTotal(v bool) ListSpecificationsOption { + return func(o *ListSpecificationsOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} // ListSpecifications list allowed site specifications for this instance. func (srv *Sites) ListSpecifications(optionalSetters ...ListSpecificationsOption) (*models.SpecificationList, error) { @@ -429,6 +462,9 @@ func (srv *Sites) ListSpecifications(optionalSetters ...ListSpecificationsOption if options.enabledSetters["Type"] { params["type"] = options.Type } + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" @@ -1024,7 +1060,7 @@ func (srv *Sites) CreateDeployment(SiteId string, Code file.InputFile, optionalS uploadId := "" - resp, err := srv.client.FileUpload(path, headers, params, paramName, uploadId) + resp, err := srv.client.FileUpload(path, headers, params, paramName, uploadId, "POST") if err != nil { return nil, err } @@ -1033,12 +1069,11 @@ func (srv *Sites) CreateDeployment(SiteId string, Code file.InputFile, optionalS if err != nil { return nil, err } - var parsed models.Deployment - err = json.Unmarshal(bytes, &parsed) - if err != nil { + parsed := models.Deployment{}.New(bytes) + if err := json.Unmarshal(bytes, parsed); err != nil { return nil, err } - return &parsed, nil + return parsed, nil } var parsed models.Deployment parsed, ok := resp.Result.(models.Deployment) diff --git a/storage/storage.go b/storage/storage.go index e8fa36cd..91cc5b94 100644 --- a/storage/storage.go +++ b/storage/storage.go @@ -645,7 +645,7 @@ func (srv *Storage) CreateFile(BucketId string, FileId string, File file.InputFi uploadId = value } - resp, err := srv.client.FileUpload(path, headers, params, paramName, uploadId) + resp, err := srv.client.FileUpload(path, headers, params, paramName, uploadId, "POST") if err != nil { return nil, err } @@ -654,12 +654,11 @@ func (srv *Storage) CreateFile(BucketId string, FileId string, File file.InputFi if err != nil { return nil, err } - var parsed models.File - err = json.Unmarshal(bytes, &parsed) - if err != nil { + parsed := models.File{}.New(bytes) + if err := json.Unmarshal(bytes, parsed); err != nil { return nil, err } - return &parsed, nil + return parsed, nil } var parsed models.File parsed, ok := resp.Result.(models.File) diff --git a/tablesdb/tables_db.go b/tablesdb/tables_db.go index 1632fbd7..d3a36cc0 100644 --- a/tablesdb/tables_db.go +++ b/tablesdb/tables_db.go @@ -239,11 +239,12 @@ func (srv *TablesDB) ListSpecifications() (*models.DedicatedDatabaseSpecificatio type ListTransactionsOptions struct { Queries []string + Total bool enabledSetters map[string]bool } func (options ListTransactionsOptions) New() *ListTransactionsOptions { - options.enabledSetters = map[string]bool{"Queries": false} + options.enabledSetters = map[string]bool{"Queries": false, "Total": false} return &options } @@ -255,6 +256,12 @@ func (srv *TablesDB) WithListTransactionsQueries(v []string) ListTransactionsOpt o.enabledSetters["Queries"] = true } } +func (srv *TablesDB) WithListTransactionsTotal(v bool) ListTransactionsOption { + return func(o *ListTransactionsOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} // ListTransactions list transactions across all databases. func (srv *TablesDB) ListTransactions(optionalSetters ...ListTransactionsOption) (*models.TransactionList, error) { @@ -267,6 +274,9 @@ func (srv *TablesDB) ListTransactions(optionalSetters ...ListTransactionsOption) if options.enabledSetters["Queries"] { params["queries"] = options.Queries } + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" diff --git a/tablesdb/tables_db_test.go b/tablesdb/tables_db_test.go index 4bfc4b63..ea684881 100644 --- a/tablesdb/tables_db_test.go +++ b/tablesdb/tables_db_test.go @@ -757,10 +757,6 @@ func TestTablesDB(t *testing.T) { "engine": "postgresql", "version": "17", "uptime": 86400, - "connections": { - "current": 12, - "max": 100 - }, "syncMode": "async", "syncDegraded": true, "syncAcknowledgements": 1, diff --git a/vectorsdb/vectors_db.go b/vectorsdb/vectors_db.go index e33b2a42..ac899c37 100644 --- a/vectorsdb/vectors_db.go +++ b/vectorsdb/vectors_db.go @@ -228,11 +228,12 @@ func (srv *VectorsDB) ListSpecifications() (*models.DedicatedDatabaseSpecificati type ListTransactionsOptions struct { Queries []string + Total bool enabledSetters map[string]bool } func (options ListTransactionsOptions) New() *ListTransactionsOptions { - options.enabledSetters = map[string]bool{"Queries": false} + options.enabledSetters = map[string]bool{"Queries": false, "Total": false} return &options } @@ -244,6 +245,12 @@ func (srv *VectorsDB) WithListTransactionsQueries(v []string) ListTransactionsOp o.enabledSetters["Queries"] = true } } +func (srv *VectorsDB) WithListTransactionsTotal(v bool) ListTransactionsOption { + return func(o *ListTransactionsOptions) { + o.Total = v + o.enabledSetters["Total"] = true + } +} // ListTransactions list transactions across all databases. func (srv *VectorsDB) ListTransactions(optionalSetters ...ListTransactionsOption) (*models.TransactionList, error) { @@ -256,6 +263,9 @@ func (srv *VectorsDB) ListTransactions(optionalSetters ...ListTransactionsOption if options.enabledSetters["Queries"] { params["queries"] = options.Queries } + if options.enabledSetters["Total"] { + params["total"] = options.Total + } headers := map[string]interface{}{} headers["X-Appwrite-Project"] = srv.client.Config["project"] headers["accept"] = "application/json" diff --git a/vectorsdb/vectors_db_test.go b/vectorsdb/vectors_db_test.go index 1bd091b6..ee74b074 100644 --- a/vectorsdb/vectors_db_test.go +++ b/vectorsdb/vectors_db_test.go @@ -1297,10 +1297,6 @@ func TestVectorsDB(t *testing.T) { "engine": "postgresql", "version": "17", "uptime": 86400, - "connections": { - "current": 12, - "max": 100 - }, "syncMode": "async", "syncDegraded": true, "syncAcknowledgements": 1,