cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

How to store and retrieve documents from DocumentStore?

Radoslaw_Szulgo
Dynatrace Guru
Dynatrace Guru

I'm a total newbie in the Document Store service. As a first step, I'd like to have something to manage documents in my app - add new ones, delete, and retrieve data. 

Senior Product Manager,
Dynatrace Managed expert
1 REPLY 1

Radoslaw_Szulgo
Dynatrace Guru
Dynatrace Guru

Hope you'll like it! It helped my team a lot to start!

DocumentStoreSandbox.tsx

 

 

 

import React, { FunctionComponent, useState, useEffect } from "react";
import { Flex, Modal, Button, TextInput, TextArea, FormField } from "@dynatrace/strato-components-preview";
import { documentsClient, CreateDocumentBody } from "@dynatrace-sdk/client-document";
import { DocumentsStoreSandboxView } from "./DocumentsStoreSandboxView";

export const DocumentStoreSandbox: FunctionComponent = () => {
  const [docData, setDocData] = useState("doc");
  const [savedDocuments, setSavedDocuments] = useState<{ id: string; name: string; version: string }[]>([]);
  const [savedDocName, setSavedDocName] = useState("default doc name");
  const [saveModalState, setSaveModalState] = useState(false);
  const [loadedOnce, setLoadedOnce] = useState(false);

  function loadDocuments() {
    const getDocumentsFromDocStore = async () => {
      const myDocs = await documentsClient.listDocuments({
        filter: "type = 'schema_documents'",
      });
      setSavedDocuments(myDocs.documents.map((o) => ({ id: o.id, name: o.name, version: o.version })));
    };
    getDocumentsFromDocStore();
  }

  function setDocFromDocStore(doc_name) {
    const obj = savedDocuments.find((o) => o.name === doc_name);

    const getDocData = async (id: string) => {
      const obj = await documentsClient.downloadDocumentContent({
        id,
      });
      const result = JSON.parse(await obj.get("text"));
      setDocData(result.docData);
    };
    if (obj !== undefined) {
      console.log("docid:" + obj.id);

      getDocData(obj.id);
    }
  }

  function addNewDocument() {
    const doc = { docData: docData };
    const document: CreateDocumentBody = {
      name: savedDocName,
      type: "schema_documents",
      content: new Blob([JSON.stringify(doc, null, 2)], {
        type: "application/json",
      }),
    };
    documentsClient.createDocument({ body: document }).then(() => {
      loadDocuments();
      setSaveModalState(false);
    });
  }

  function saveDocData() {
    setSavedDocName("");
    setSaveModalState(true);
  }

  function shareDocument(evt) {
    const target = evt.target.localName == "svg" ? evt.target : evt.target.parentNode;
    const docTitle = target?.parentNode?.parentNode?.children[0].textContent;
    const obj = savedDocuments.find((o) => o.name === docTitle);

    const shareDocument = async (obj: object) => {
      (window as any).dtSdk.shareDocument(obj["id"]);
    };
    if (obj !== undefined) {
      shareDocument(obj);
    }
  }
  function removeDocument(evt) {
    const target = evt.target.localName == "svg" ? evt.target : evt.target.parentNode;
    const docTitle = target?.parentNode?.parentNode?.children[0].textContent;
    const obj = savedDocuments.find((o) => o.name === docTitle);

    const deleteDocument = async (obj: object) => {
      const response = await documentsClient.deleteDocument({
        id: obj["id"],
        optimisticLockingVersion: obj["version"],
      });
      console.log(JSON.stringify(response));
      loadDocuments();
    };
    if (obj !== undefined) {
      deleteDocument(obj);
    }
  }

  useEffect(() => {
    if (!loadedOnce) {
      loadDocuments();
      setLoadedOnce(true);
    }
  }, [loadedOnce]);

  return (
    <Flex flexDirection="column" width={"100%"}>
      <Flex flexDirection="row">
        <Button onClick={saveDocData}>Save document</Button>
      </Flex>
      <Flex flexDirection="row">
        <Flex flexDirection="column" width={"20%"} padding={2}>
          <DocumentsStoreSandboxView
            title={"My documents"}
            documents={savedDocuments}
            onRemove={(evt) => {
              removeDocument(evt);
            }}
            onShare={(evt) => {
              shareDocument(evt);
            }}
            onClick={(evt) => {
              setDocFromDocStore((evt.target as HTMLElement).innerText);
            }}
          />
        </Flex>
        <Flex flexDirection="column" width={"80%"} padding={2}>
          <TextArea value={docData} onChange={setDocData} />
        </Flex>
        <Modal
          title="Save new document"
          show={saveModalState}
          onDismiss={() => setSaveModalState(false)}
          dismissible={true}
        >
          <FormField label="Document Name">
            <TextInput placeholder={"Enter document name"} value={savedDocName} onChange={setSavedDocName} />
          </FormField>
          <Button onClick={() => setSaveModalState(false)}>Cancel</Button>
          <Button onClick={addNewDocument}>Save document</Button>
        </Modal>
      </Flex>
    </Flex>
  );
};

 

 

 

 

DocumentsStoreSandboxView.tsx:

 

 

 

import React from "react";
import { Flex, Button, Paragraph } from "@dynatrace/strato-components-preview";
import { DeleteIcon, ShareIcon } from "@dynatrace/strato-icons";

export interface DocumentsStoreSandboxViewProps {
  title: string;
  documents: object[];
  onRemove(event): void;
  onClick(event): void;
  onShare(event): void;
}

export const DocumentsStoreSandboxView = (props: DocumentsStoreSandboxViewProps) => {
  const { title, documents } = props;

  return (
    <Flex width={"100%"} flexDirection="column">
      <Paragraph>{title}</Paragraph>
      <div className={"documents"}>
        {documents.map((k) => (
          <div key={"doc_" + k["id"]}>
            <Button className={"item"} onClick={props.onClick} key={k["id"]}>
              {k["name"]}
            </Button>
            <div className={"remove"} key={"rem_" + k["id"]} onClick={props.onRemove}>
              <DeleteIcon />
            </div>
            <div className={"share"} key={"share_" + k["id"]} onClick={props.onShare}>
              <ShareIcon />
            </div>
            <div className={"clr"}></div>
          </div>
        ))}
      </div>
    </Flex>
  );
};

 

 

 

 

and:

Document.tsx (page)

 

 

 

import React from "react";
import { Flex } from "@dynatrace/strato-components-preview";
import { IntlProvider } from 'react-intl';
import {DocumentStoreSandbox} from "../components/DocumentStoreSandbox";

export const Document = () => {

    return (
        <Flex flexDirection="row" padding={2}>
            <IntlProvider locale="en">
                <DocumentStoreSandbox />
            </IntlProvider>
        </Flex>
    );
};

 

 

 

Senior Product Manager,
Dynatrace Managed expert