Skip to content

Instantly share code, notes, and snippets.

@AsishP
Last active May 6, 2019 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AsishP/d083f2447cfab560649d8f33846cc4db to your computer and use it in GitHub Desktop.
Save AsishP/d083f2447cfab560649d8f33846cc4db to your computer and use it in GitHub Desktop.
Add/Update with SP Http Client
try
{
let addorUpdateObj : any = {
AuthorId : customObj.user.id,
__metadata : {
'type': `SP.Data.CustomListItem`
}
}
console.log(`Sending object ${addorUpdateObj}`);
let body: string = JSON.stringify(addorUpdateObj);
let spHttpClient : SPHttpClient = context.spHttpClient;
let postURL: string = `${context.pageContext.web.absoluteUrl}/_api/web/lists/GetByTitle('${listTitle}')/Items` ;
let Action = 'POST';
if(customObj.id !== 0)
{
postURL = postURL + `('${customObj.id}')`;
Action = 'MERGE';
console.log(`update called ${postURL}`);
spHttpClient.post(postURL,
SPHttpClient.configurations.v1,
{
headers: {
'Accept': 'application/json;odata=nometadata',
'Content-type': 'application/json;odata=verbose',
'odata-version': '',
'IF-MATCH': '*',
'X-HTTP-Method': Action
},
body: body
}).then((response: SPHttpClientResponse) => {
console.log('Save result ' + response.ok);
if(response.ok)
{
resolve(true);
}
else
reject("Error while saving data");
});
}
else
{
console.log(`add called ${postURL}`);
spHttpClient.post(postURL,
SPHttpClient.configurations.v1,
{
headers: {
'Accept': 'application/json;odata=verbose',
'Content-type': 'application/json;odata=verbose',
'odata-version': ''
},
body: body
}).then((response: SPHttpClientResponse) => {
console.log('Save result ' + response.ok);
if(response.ok)
{
resolve(true);
}
else
reject("Error while saving data");
});
}
} catch(error)
{
console.log(error);
throw(error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment