In textMetadata use new fields API result

Resolves #18

Change-Id: I68ee8c82457e1e09c50a8490f1e6443e7a2f06c3
diff --git a/NAMESPACE b/NAMESPACE
index 3261a8e..53ab148 100644
--- a/NAMESPACE
+++ b/NAMESPACE
@@ -108,4 +108,5 @@
 importFrom(tidyr,complete)
 importFrom(tidyr,expand_grid)
 importFrom(tidyr,pivot_longer)
+importFrom(tidyr,pivot_wider)
 importFrom(urltools,url_encode)
diff --git a/R/textMetadata.R b/R/textMetadata.R
index 834fa11..bc07be0 100644
--- a/R/textMetadata.R
+++ b/R/textMetadata.R
@@ -18,6 +18,8 @@
 #'
 #' @importFrom urltools url_encode
 #' @importFrom dplyr bind_rows relocate mutate
+#' @importFrom tibble as_tibble
+#' @importFrom tidyr pivot_wider
 #'
 #' @examples
 #' \dontrun{
@@ -41,14 +43,25 @@
     if(is.null(res)) {
       res <- tibble(errors="API request failed")
     } else {
-      res <- lapply(res, function(x) paste0(x, collapse = "\\t")) # flatten list
-      res <- as_tibble(res) %>%
-        head(n=1) %>%
-        mutate(
-          requestUrl = url,
-          textSigle = textSigle,
-          webUIRequestUrl = paste0(kco@KorAPUrl, sprintf('?q=<base/s=t>&cq=textSigle+%%3D+"%s"', url_encode(enc2utf8(textSigle))))) %>%
+      if ("document" %in% names(res) & "fields" %in% names(res$document)) {
+        res <- as_tibble(res$document$fields) %>%
+          select(key, value) %>%
+          tidyr::pivot_wider(names_from = key, values_from = value, names_repair = "unique") %>%
+          mutate(
+            textSigle = as.character(textSigle),
+            requestUrl = url,
+            webUIRequestUrl = paste0(kco@KorAPUrl, sprintf('?q=<base/s=t>&cq=textSigle+%%3D+"%s"', url_encode(enc2utf8(textSigle))))) %>%
         relocate(textSigle)
+      } else {
+        res <- lapply(res, function(x) paste0(x, collapse = "\\t")) # flatten list
+        res <- as_tibble(res) %>%
+          head(n=1) %>%
+          mutate(
+            requestUrl = url,
+            textSigle = textSigle,
+            webUIRequestUrl = paste0(kco@KorAPUrl, sprintf('?q=<base/s=t>&cq=textSigle+%%3D+"%s"', url_encode(enc2utf8(textSigle))))) %>%
+          relocate(textSigle)
+      }
     }
     res
   }