github.com/elliott5/community@v0.14.1-0.20160709191136-823126fb026a/sdk/templates.go (about) 1 // Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved. 2 // 3 // This software (Documize Community Edition) is licensed under 4 // GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html 5 // 6 // You can operate outside the AGPL restrictions by purchasing 7 // Documize Enterprise Edition and obtaining a commercial license 8 // by contacting <sales@documize.com>. 9 // 10 // https://documize.com 11 12 package documize 13 14 import ( 15 "encoding/json" 16 "errors" 17 "fmt" 18 "io/ioutil" 19 "net/http" 20 21 "github.com/documize/community/documize/api/entity" 22 ) 23 24 // GetTemplates returns the available templates; from the stock templates if useStock is set. 25 func (c *Client) GetTemplates(useStock bool) (temps []entity.Template, err error) { 26 url := fmt.Sprintf("%s/api/templates", 27 c.BaseURL) 28 if useStock { 29 url += "/stock" 30 } 31 req, err := http.NewRequest("GET", url, nil) 32 if err != nil { 33 return nil, err 34 } 35 req.Header.Add(HeaderAuthTokenName, c.Auth.Token) 36 resp, errDo := c.Client.Do(req) 37 if errDo != nil { 38 return nil, errDo 39 } 40 defer resp.Body.Close() // ignore error 41 b, errRA := ioutil.ReadAll(resp.Body) 42 if errRA != nil { 43 return nil, errRA 44 } 45 if isError(string(b)) { 46 return nil, errors.New(trimErrors(string(b))) 47 } 48 err = json.Unmarshal(b, &temps) 49 if err != nil { 50 return nil, err 51 } 52 return temps, nil 53 } 54 55 // StartDocumentFromTemplate returns the documentID created in the given folderID from the given templateID, 56 // using either a stock template if isStock==true or a saved template. 57 func (c *Client) StartDocumentFromTemplate(isStock bool, templateID, folderID string) (DocumentID string, err error) { 58 url := fmt.Sprintf("%s/api/templates/%s/folder/%s?type=", 59 c.BaseURL, templateID, folderID) 60 if isStock { 61 url += "stock" 62 } else { 63 url += "saved" 64 } 65 req, err := http.NewRequest("POST", url, nil) 66 if err != nil { 67 return "", err 68 } 69 req.Header.Add(HeaderAuthTokenName, c.Auth.Token) 70 resp, err := c.Client.Do(req) 71 if err != nil { 72 return "", err 73 } 74 defer resp.Body.Close() // ignore error 75 b, err := ioutil.ReadAll(resp.Body) 76 if err != nil { 77 return "", err 78 } 79 if isError(string(b)) { 80 return "", errors.New(trimErrors(string(b))) 81 } 82 var model entity.Document 83 err = json.Unmarshal(b, &model) 84 if err != nil { 85 return "", err 86 } 87 if model.RefID == "" { 88 return "", errors.New("empty DocumentID returned") 89 } 90 return model.RefID, nil 91 }