pekko/akka-docs/rst/scala/http/routing-dsl/directives/marshalling-directives/completeWith.rst
2016-01-14 00:31:03 +01:00

45 lines
1.9 KiB
ReStructuredText

.. _-completeWith-:
completeWith
============
Signature
---------
.. includecode2:: /../../akka-http/src/main/scala/akka/http/scaladsl/server/directives/MarshallingDirectives.scala
:snippet: completeWith[T]
Description
-----------
Uses the marshaller for a given type to produce a completion function that is passed to its
inner route. You can use it to decouple marshaller resolution from request completion.
The ``completeWith`` directive works in conjuction with ``instanceOf`` and ``spray.httpx.marshalling``
to convert higher-level (object) structure into some lower-level serialized "wire format".
:ref:`The marshalling documentation <http-marshalling-scala>` explains this process in detail.
This directive simplifies exposing types to clients via a route while providing some
form of access to the current context.
``completeWith`` is similar to ``handleWith``. The main difference is with ``completeWith`` you must eventually call
the completion function generated by ``completeWith``. ``handleWith`` will automatically call ``complete`` when the
``handleWith`` function returns.
Examples
--------
The following example uses ``spray-json`` to marshall a simple ``Person`` class to a json
response. It utilizes ``SprayJsonSupport`` via the ``PersonJsonSupport`` object as the in-scope
unmarshaller.
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/MarshallingDirectivesExamplesSpec.scala
:snippet: person-json-support
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/MarshallingDirectivesExamplesSpec.scala
:snippet: person-case-class
The ``findPerson`` takes an argument of type ``Person => Unit`` which is generated by the ``completeWith``
call. We can handle any logic we want in ``findPerson`` and call our completion function to
complete the request.
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/MarshallingDirectivesExamplesSpec.scala
:snippet: example-completeWith-with-json