github.com/yaegashi/msgraph.go@v0.1.4/beta/msgraph.go (about)

     1  // Code generated by msgraph.go/gen DO NOT EDIT.
     2  
     3  package msgraph
     4  
     5  import (
     6  	"bytes"
     7  	"context"
     8  	"encoding/json"
     9  	"fmt"
    10  	"io"
    11  	"io/ioutil"
    12  	"net/http"
    13  	"net/url"
    14  	"strconv"
    15  	"time"
    16  
    17  	"github.com/rickb777/date/period"
    18  	"github.com/yaegashi/msgraph.go/jsonx"
    19  )
    20  
    21  // Binary is type alias for Edm.Binary
    22  type Binary []byte
    23  
    24  // Stream is type alias for Edm.Stream
    25  type Stream []byte
    26  
    27  // UUID is type alias for Edm.Guid
    28  type UUID string
    29  
    30  // Date is type alias for Edm.Date
    31  type Date string
    32  
    33  // NewDate creates Date from time.Time
    34  func NewDate(t time.Time) *Date {
    35  	s := t.Format("2006-01-02")
    36  	return (*Date)(&s)
    37  }
    38  
    39  // Time converts Date to time.Time
    40  func (d *Date) Time() (time.Time, error) {
    41  	return time.Parse("2006-01-02", string(*d))
    42  }
    43  
    44  // TimeOfDay is type alis for Edm.TimeOfDay
    45  type TimeOfDay string
    46  
    47  // NewTimeOfDay creates NewTimeOfDay from time.Time
    48  func NewTimeOfDay(t time.Time) *TimeOfDay {
    49  	s := t.Format("15:04:05")
    50  	return (*TimeOfDay)(&s)
    51  }
    52  
    53  // Time converts TimeOfDay to time.Time
    54  func (t *TimeOfDay) Time() (time.Time, error) {
    55  	return time.Parse("15:04:05", string(*t))
    56  }
    57  
    58  // Duration is type alias for Edm.Duration
    59  type Duration string
    60  
    61  // NewDuration creates Duration from time.Duration
    62  func NewDuration(d time.Duration) *Duration {
    63  	p, _ := period.NewOf(d)
    64  	s := p.String()
    65  	return (*Duration)(&s)
    66  }
    67  
    68  // Time converts Duration to time.Duration
    69  func (d *Duration) Time() (time.Duration, error) {
    70  	p, err := period.Parse(string(*d))
    71  	if err != nil {
    72  		return 0, err
    73  	}
    74  	return p.DurationApprox(), nil
    75  }
    76  
    77  // Object is the common ancestor of all models
    78  type Object struct {
    79  	// AdditionalData contains all other fields not defined above
    80  	AdditionalData map[string]interface{} `json:"-" jsonx:"true"`
    81  }
    82  
    83  // SetAdditionalData sets object's additional data
    84  func (o *Object) SetAdditionalData(key string, val interface{}) {
    85  	if o.AdditionalData == nil {
    86  		o.AdditionalData = map[string]interface{}{key: val}
    87  	} else {
    88  		o.AdditionalData[key] = val
    89  	}
    90  }
    91  
    92  // GetAdditionalData gets object's additional data
    93  func (o *Object) GetAdditionalData(key string) (interface{}, bool) {
    94  	if o.AdditionalData == nil {
    95  		return nil, false
    96  	} else {
    97  		val, ok := o.AdditionalData[key]
    98  		return val, ok
    99  	}
   100  }
   101  
   102  // ErrorObject is common error object
   103  type ErrorObject struct {
   104  	Code    string `json:"code"`
   105  	Message string `json:"message"`
   106  	Object
   107  }
   108  
   109  // ErrorResponse is common error response
   110  type ErrorResponse struct {
   111  	ErrorObject ErrorObject    `json:"error"`
   112  	Response    *http.Response `json:"-"`
   113  	Object
   114  }
   115  
   116  // Error implements error interface
   117  func (r *ErrorResponse) Error() string {
   118  	b, _ := jsonx.Marshal(r)
   119  	return fmt.Sprintf("%s: %s", r.Status(), string(b))
   120  }
   121  
   122  // Status returns status, "000 Unknown" if response is nil
   123  func (r *ErrorResponse) Status() string {
   124  	if r.Response == nil {
   125  		return "000 Unknown"
   126  	}
   127  	return r.Response.Status
   128  }
   129  
   130  // StatusCode returns status code, 0 if response is nil
   131  func (r *ErrorResponse) StatusCode() int {
   132  	if r.Response == nil {
   133  		return 0
   134  	}
   135  	return r.Response.StatusCode
   136  }
   137  
   138  // Paging is sturct returned to paging requests
   139  type Paging struct {
   140  	NextLink string          `json:"@odata.nextLink"`
   141  	Value    json.RawMessage `json:"value"`
   142  }
   143  
   144  // BaseRequestBuilder is base reuqest builder
   145  type BaseRequestBuilder struct {
   146  	baseURL       string
   147  	client        *http.Client
   148  	requestObject interface{}
   149  }
   150  
   151  // URL returns URL
   152  func (r *BaseRequestBuilder) URL() string {
   153  	return r.baseURL
   154  }
   155  
   156  // SetURL sets the baseURL
   157  func (r *BaseRequestBuilder) SetURL(baseURL string) {
   158  	r.baseURL = baseURL
   159  }
   160  
   161  // BaseRequest is base request
   162  type BaseRequest struct {
   163  	baseURL       string
   164  	client        *http.Client
   165  	requestObject interface{}
   166  	header        http.Header
   167  	query         url.Values
   168  }
   169  
   170  // URL returns URL with queries
   171  func (r *BaseRequest) URL() string {
   172  	var query string
   173  	if r.query != nil {
   174  		query = "?" + r.query.Encode()
   175  	}
   176  	return r.baseURL + query
   177  }
   178  
   179  // Client returns HTTP client
   180  func (r *BaseRequest) Client() *http.Client {
   181  	return r.client
   182  }
   183  
   184  // Header returns headers of the request
   185  func (r *BaseRequest) Header() http.Header {
   186  	if r.header == nil {
   187  		r.header = http.Header{}
   188  	}
   189  	return r.header
   190  }
   191  
   192  // Query returns queries of the request
   193  func (r *BaseRequest) Query() url.Values {
   194  	if r.query == nil {
   195  		r.query = url.Values{}
   196  	}
   197  	return r.query
   198  }
   199  
   200  // Expand adds $expand query
   201  func (r *BaseRequest) Expand(value string) {
   202  	if r.query == nil {
   203  		r.query = url.Values{}
   204  	}
   205  	r.query.Add("$expand", value)
   206  }
   207  
   208  // Select adds $select query
   209  func (r *BaseRequest) Select(value string) {
   210  	if r.query == nil {
   211  		r.query = url.Values{}
   212  	}
   213  	r.query.Add("$select", value)
   214  }
   215  
   216  // Top adds $top query
   217  func (r *BaseRequest) Top(value int) {
   218  	if r.query == nil {
   219  		r.query = url.Values{}
   220  	}
   221  	r.query.Add("$top", strconv.Itoa(value))
   222  }
   223  
   224  // Filter adds $filter query
   225  func (r *BaseRequest) Filter(value string) {
   226  	if r.query == nil {
   227  		r.query = url.Values{}
   228  	}
   229  	r.query.Add("$filter", value)
   230  }
   231  
   232  // Skip adds $skip query
   233  func (r *BaseRequest) Skip(value int) {
   234  	if r.query == nil {
   235  		r.query = url.Values{}
   236  	}
   237  	r.query.Add("$skip", strconv.Itoa(value))
   238  }
   239  
   240  // OrderBy adds $orderby query
   241  func (r *BaseRequest) OrderBy(value string) {
   242  	if r.query == nil {
   243  		r.query = url.Values{}
   244  	}
   245  	r.query.Add("$orderby", value)
   246  }
   247  
   248  // NewRequest returns new HTTP request
   249  func (r *BaseRequest) NewRequest(method, path string, body io.Reader) (*http.Request, error) {
   250  	req, err := http.NewRequest(method, r.baseURL+path, body)
   251  	if err != nil {
   252  		return nil, err
   253  	}
   254  	if r.header != nil {
   255  		for key, values := range r.header {
   256  			for _, value := range values {
   257  				req.Header.Add(key, value)
   258  			}
   259  		}
   260  	}
   261  	return req, nil
   262  }
   263  
   264  // NewJSONRequest returns new HTTP request with JSON payload
   265  func (r *BaseRequest) NewJSONRequest(method, path string, obj interface{}) (*http.Request, error) {
   266  	buf := &bytes.Buffer{}
   267  	if obj != nil {
   268  		err := jsonx.NewEncoder(buf).Encode(obj)
   269  		if err != nil {
   270  			return nil, err
   271  		}
   272  	}
   273  	req, err := r.NewRequest(method, path, buf)
   274  	if err != nil {
   275  		return nil, err
   276  	}
   277  	if obj != nil {
   278  		req.Header.Add("Content-Type", "application/json")
   279  	}
   280  	return req, nil
   281  }
   282  
   283  // DecodeJSONResponse decodes HTTP response with JSON payload
   284  func (r *BaseRequest) DecodeJSONResponse(res *http.Response, obj interface{}) error {
   285  	switch res.StatusCode {
   286  	case http.StatusOK, http.StatusCreated:
   287  		if obj != nil {
   288  			err := jsonx.NewDecoder(res.Body).Decode(obj)
   289  			if err != nil {
   290  				return err
   291  			}
   292  		}
   293  		return nil
   294  	case http.StatusNoContent:
   295  		return nil
   296  	default:
   297  		b, _ := ioutil.ReadAll(res.Body)
   298  		errRes := &ErrorResponse{Response: res}
   299  		err := jsonx.Unmarshal(b, errRes)
   300  		if err != nil {
   301  			return fmt.Errorf("%s: %s", res.Status, string(b))
   302  		}
   303  		return errRes
   304  	}
   305  }
   306  
   307  // JSONRequest issues HTTP request with JSON payload
   308  func (r *BaseRequest) JSONRequest(ctx context.Context, method, path string, reqObj, resObj interface{}) error {
   309  	req, err := r.NewJSONRequest(method, path, reqObj)
   310  	if err != nil {
   311  		return err
   312  	}
   313  	if ctx != nil {
   314  		req = req.WithContext(ctx)
   315  	}
   316  	res, err := r.client.Do(req)
   317  	if err != nil {
   318  		return err
   319  	}
   320  	defer res.Body.Close()
   321  	return r.DecodeJSONResponse(res, resObj)
   322  }
   323  
   324  // GraphServiceRequestBuilder is GraphService reuqest builder
   325  type GraphServiceRequestBuilder struct {
   326  	BaseRequestBuilder
   327  }
   328  
   329  // NewClient returns GraphService request builder with default base URL
   330  func NewClient(cli *http.Client) *GraphServiceRequestBuilder {
   331  	return &GraphServiceRequestBuilder{
   332  		BaseRequestBuilder: BaseRequestBuilder{baseURL: defaultBaseURL, client: cli},
   333  	}
   334  }