The annotation %rest:cookie-param
is provided for accessing
Request HTTP Cookies sent by the client. Take the following HTTP request
GET /get-session-info HTTP/1.1 Host: localhost Cookie: Session-ID=ks73jaxbeh2jzb
The following function accesses the Session-ID Cookie
declare
%rest:path("/get-session-info")
%rest:cookie-param('Session-ID', '{$id}')
function session-info($id as xs:string) {
fn:collection('sessions')/session[@id = $id]
};
Unfortunately, due to a limitation in MarkLogic, only one
%rest:cookie-param
annotation can be used per function.
If you wish to access more than one cookie in same function, use
numbered annotations such as
%rest:cookie-param-1
,
%rest:cookie-param-2
,
%rest:cookie-param-3
etc.
Given the following HTTP Request
GET /sample-page HTTP/1.1 Host: localhost Cookie: yummy_cookie=choco; tasty_cookie=strawberry
The following XQuery function is able to access both cookies sent by the client
declare
%rest:path("/sample-page")
%rest:cookie-param-1('yummy_cookie', '{$yummy}')
%rest:cookie-param-2('tasty_cookie', '{$tasty}')
function sample-page($yummy as xs:string, $tasty as xs:string) {
<cookies>
<yummy>{$yummy}</yummy>
<tasty>{$tasty}</tasty>
</cookies>
};
XQRS will automatically convert the Cookie Parameter into
the required parameter type at runtime for you, providing
the parameter type inherits from xs:anyAtomicType
Parameters received from Cookie Parameters can be optional and
as such the occurrence indicator on those parameters can be '?
'.
declare
%rest:path("/my-little-service")
%rest:cookie-param('Optional-Cookie', '{$opt}')
function optional($opt as xs:date?) {
if(fn:exists($opt)) then
'got date ' || $opt
else
'optional-param not given.'
};
If automatic type conversion is not possible, for instance the parameter expects a date but the value given for that parameter can not be cast to a date then an exception is thrown explaining this.
You can give Cookie Parameters default values, in case the client has not given a value for that parameter. Consider the following example
declare
%rest:path("/document-in-collection")
%rest:cookie-param-1('X-Collection', '{$col}', 'my-default')
%rest:cookie-param-2('X-ID', '{$id}', '1234')
function optional($col as xs:string, $id as xs:integer) {
fn:collection($col)/doc[@id = $id]
};