Exemplo n.º 1
0
// IntellectualObjectSave saves the intellectual object to Pharos. If the
// object has an ID of zero, this performs a POST to create a new
// Intellectual Object. If the ID is non-zero, this updates the existing
// object with a PUT. The response object will contain a new copy of the
// IntellectualObject if it was successfully saved.
func (client *PharosClient) IntellectualObjectSave(obj *models.IntellectualObject) *PharosResponse {
	// Set up the response object
	resp := NewPharosResponse(PharosIntellectualObject)
	resp.objects = make([]*models.IntellectualObject, 1)

	// URL and method
	// Note that POST URL takes an institution identifier, while
	// the PUT URL takes an object identifier.
	relativeUrl := fmt.Sprintf("/api/%s/objects/%s", client.apiVersion, obj.Institution)
	httpMethod := "POST"
	if obj.Id > 0 {
		// PUT URL looks like /api/v2/objects/college.edu%2Fobject_name
		relativeUrl = fmt.Sprintf("/api/%s/objects/%s", client.apiVersion, escapeSlashes(obj.Identifier))
		httpMethod = "PUT"
	}
	absoluteUrl := client.BuildUrl(relativeUrl)

	// Prepare the JSON data
	postData, err := obj.SerializeForPharos()
	if err != nil {
		resp.Error = err
	}

	// Run the request
	client.DoRequest(resp, httpMethod, absoluteUrl, bytes.NewBuffer(postData))
	if resp.Error != nil {
		return resp
	}

	// Parse the JSON from the response body
	intelObj := &models.IntellectualObject{}
	resp.Error = json.Unmarshal(resp.data, intelObj)
	if resp.Error == nil {
		resp.objects[0] = intelObj
	}
	return resp
}