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

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