1. In the TutorialPublish server module, select the PutContact server routine:
Srvroutine Name(PutContact) Response(*HTTP #Context)
Endroutine
2. Replace it with the code below.
3. Compile the server module.
Srvroutine Name(PutContact) Response(*HTTP
#Context)
Define_Com Class(#PRIM_JSON.Document)
Name(#Document)
Define_Com Class(#PRIM_JSON.Object) Name(#RequestData)
Reference(*DYNAMIC)
Define_Com Class(#PRIM_IOC.StringWriter)
Name(#StringWriter)
Define_Com Class(#PRIM_JSON.Writer) Name(#Writer)
Textwriter(#StringWriter)
Group_By Name(#UpdateContact)
Fields(#xContactFirstName #xContactLastName)
#Resource := "Put
/Contact/{ContactID}"
* Default the status response to Server
Error
#HttpStatus := 500
* Validate the incoming
content
#Document.LoadFromString(
#Context.Request.Content.FormVariables<"*POSTDATA">.GetText )
* If
there is no RootNode then the content is either non existent or no valid JSON
format.
If (#Document.RootNode *Is
*Null)
#Com_Owner.MakeBadRequestResponse Context(#Context)
Path(#Context.Request.Path) Resourcename(#Resource) Status(#HttpStatus)
Additionalmessage("Document is null or it doesn't contain valid JSON.
")
Return
Endif
* Instantiate the RootNode as a JSON
object.
#RequestData <= #Document.RootNode *As #PRIM_JSON.Object
If
((#RequestData *Is *Null))
#Com_Owner.MakeBadRequestResponse
Context(#Context) Path(#Context.Request.Path) Resourcename(#Resource)
Status(#HttpStatus) Additionalmessage("Document has no Root Node or Root Node is
Null. Requested data is Null or not valid Json.")
Return
Endif
* So
far so good. Default the status response to not found
#HttpStatus :=
404
* Get the {ContactId} parameter which is the Key to the xContacts
table.
If (#Context.Request.PathParameters.TryParseAsInt32( "ContactId",
#xContactIdentification ))
* Read the First and Last Name from the
database with the supplied key
Fetch Fields(#UpdateContact)
From_File(xContacts) With_Key(#xContactIdentification)
* When found,
update the Contact fields with the requested values
If_Status
Is(*OKAY)
#xContactFirstName :=
#RequestData<"FirstName">.AsString
#xContactLastName :=
#RequestData<"LastName">.AsString
Update Fields(#UpdateContact)
In_File(xContacts) Issue_Msg(*YES)
If_Status Is(*OKAY)
#HttpStatus
:= 200
Endif
Endif
Endif
If (#HttpStatus = 200)
*
All good, write out an informational message response
#Writer.TextWriter
<= #StringWriter
#Writer.WriteString( ("Contact " +
#xContactIdentification.AsString + " Updated Successfully.")
)
#Context.Response.HttpStatus :=
#HttpStatus
#Context.Response.ContentType :=
"application/json"
#Context.Response.ContentString :=
#StringWriter.Text
Else
* Send a 404 not found
response
#Com_Owner.MakeBadRequestResponse Context(#Context)
Path(#Context.Request.Path) Resourcename("Invalid or no Contact ID ")
Status(#HttpStatus)
Endif
Endroutine