1. In the TutorialPublish server module, select the GetContacts server routine:
Srvroutine Name(GetContacts) Response(*HTTP #context)
Endroutine
2. Replace it with the code below.
3. Then compile the server module.
Srvroutine Name(GetContacts) Response(*HTTP
#context)
Define_Com Class(#PRIM_IOC.StringWriter)
Name(#StringWriter)
Define_Com Class(#PRIM_JSON.Writer) Name(#Writer)
Textwriter(#StringWriter)
Define_Com Class(#STD_STRNG)
Name(#SearchString)
Define_Com Class(#std_int) Name(#SetLimit)
Define_Com
Class(#std_int) Name(#Counter)
* Set limit number contacts to
get
#SetLimit := 20
#Counter := 0
* Get the search string from the
query parameters.
#SearchString :=
#Context.Request.QueryParameters<"SearchString">.Value.UpperCase
*
Return the contacts as an array of objects. In our example, each object in the
list has these properties:
*
* "ContactId"
* "FirstName"
*
"LastName"
*
* Start writing out the JSON response as an
Array.
#Writer.BeginArray
* Select the fields from the Database
table xContacts. For the purpose of this example we are only adding the first 20
records as per #SetLimit value.
Select Fields(#ContactFields)
From_File(xContacts)
Leave If(#Counter > #SetLimit)
* When the
SearchString has a value, add only the Contacts where the First and/or Last Name
contain the SearchString
If ((#SearchString = "") *OrIf
#xContactFirstName.UpperCase.Contains( #SearchString ) *OrIf
#xContactLastName.UpperCase.Contains( #SearchString ))
#Counter +=
1
* Begin to write the JSON object
#Writer.BeginObject
* Write
out the values obtained from the Database table:
#Writer.WriteInt32(
#xContactIdentification, "ContactId" )
#Writer.WriteString(
#xContactFirstName, "FirstName" )
#Writer.WriteString( #xContactLastName,
"LastName" )
* End the JSON object currently being
written
#Writer.EndObject
Endif
Endselect
* End the JSON
array currently being written
#Writer.EndArray
If (#Counter =
0)
* Empty Array means table has no Contacts. Manufacture a 404
response.
#com_owner.MakeBadRequestResponse Context(#context)
Path(#Context.Request.Path) Resourcename("Get /Contacts") Status(404)
Additionalmessage("No record found in table
xContacts")
Else
*
#Context.Response.HttpStatus :=
200
#Context.Response.ContentType :=
"application/json"
#Context.Response.ContentString :=
#StringWriter.Text
Endif
Endroutine