summaryrefslogtreecommitdiffstats
path: root/lib/Controller
diff options
context:
space:
mode:
authorPaul Tirk <paultirk@paultirk.com>2020-12-26 22:39:42 +0000
committerSean Molenaar <SMillerDev@users.noreply.github.com>2021-04-08 10:23:11 +0200
commit2a2d7194ee53f75b5670317a907e12071ddc5356 (patch)
tree65c01a2fed82844086e1bda2dad56c4a9d7a3fb7 /lib/Controller
parentcc9c64d69bc1d02ecf290bb34b9c971b58adf0a8 (diff)
add api v2 response trait
Signed-off-by: Paul Tirk <paultirk@paultirk.com>
Diffstat (limited to 'lib/Controller')
-rw-r--r--lib/Controller/ApiV2ResponseTrait.php59
1 files changed, 59 insertions, 0 deletions
diff --git a/lib/Controller/ApiV2ResponseTrait.php b/lib/Controller/ApiV2ResponseTrait.php
new file mode 100644
index 000000000..8f0ff5866
--- /dev/null
+++ b/lib/Controller/ApiV2ResponseTrait.php
@@ -0,0 +1,59 @@
+<?php
+
+namespace OCA\News\Controller;
+
+use \OCP\AppFramework\Http;
+use \OCP\AppFramework\Http\JSONResponse;
+
+use \OCA\News\Db\IAPI;
+
+trait ApiV2ResponseTrait
+{
+ /**
+ * Serialize all data
+ *
+ * @param mixed $data IAPI or array,
+ * anything else will return an empty array
+ *
+ * @return array
+ */
+ public function serialize($data): array
+ {
+ if ($data instanceof IAPI) {
+ return $data->toAPI2();
+ }
+
+ $return = [];
+ if (!is_array($data)) {
+ return $return;
+ }
+
+ foreach ($data as $entity) {
+ if ($entity instanceof IAPI) {
+ $return[] = $entity->toAPI2();
+ }
+ }
+ return $return;
+ }
+
+ public function response($data, $code=Http::STATUS_OK)
+ {
+ return new JSONResponse($data, $code);
+ }
+
+ /**
+ * @param \Exception $exception
+ * @param int $code
+ * @return \OCP\AppFramework\Http\JSONResponse
+ */
+ public function errorResponse(\Exception $exception, $code)
+ {
+ return new JSONResponse([
+ 'error' => [
+ 'code' => $exception->getCode(),
+ 'message' => $exception->getMessage()
+ ]
+ ], $code);
+ }
+
+}