Working With Appwrite Databases, Vue, Ionic & Capacitor
Tags: vue, appwrite, webdev, ionic
Published: 2023-05-18 02:43:34

>[Appwrite](https://appwrite.io/) - Build Fast. Scale Big. All in One Place.
Appwrite is a backend platform for developing Web, Mobile, and Flutter applications. Built with the open source community and optimized for a developer experience in the coding languages you love.

This video series will cover
- login ( Part I )
- logout ( Part I )
- create account ( Part I )
- re establish previous session ( Part I )
- **add documents ( Part II )**
- **list documents ( Part II )**
- subscribe to events when collection is updated  (Part III )
- upload images( Part III )
- associate images with documents( Part III )

In this first video we will show step by step how to get started with [Appwrite Cloud](https://appwrite.io/public-beta) using Vue JS Ionic Framework & Capacitor including login, logout, and creating an account, working with Appwrite Cloud Instance.

To modularize the code, we will be creating composables to manage integration with the [Appwrite Web SDK](https://appwrite.io/docs).
- useAppwrite
- useAccount
- useDatabases
- useStorage

[Ionic Framework components](https://ionicframework.com/docs/) are used to create the mobile interface and [Ionic Capacitor](https://capacitorjs.com/) will be used to package the web application for deployment on to mobile devices.


### Video
{% youtube 21i9xy4rlc4 %}


### Code Changes

#### useAppwrite composable
- created `ref` for appwrite `databases` object
- create `CONFIG` object to export `DATABASE_ID` and `COLLECTION_ID`

```javascript
import { Client, Account, ID, Databases } from "appwrite";
import { ref } from "vue";

const accountRef = ref<Account>();
const databaseRef = ref<Databases>()

export const useAppwrite = () => {
  console.log(import.meta.env.VITE_ENDPOINT)
  const client = new Client()
    .setEndpoint(import.meta.env.VITE_ENDPOINT)
    .setProject(import.meta.env.VITE_PROJECT);

    accountRef.value = new Account(client);
    databaseRef.value = new Databases(client);

  return {
    account: accountRef,
    database: databaseRef,
    ID: ID,
    CONFIG : {
      DATABASE_ID : import.meta.env.VITE_DATABASE_ID,
      COLLECTION_ID : import.meta.env.VITE_COLLECTION_ID
    }
  };
};
```

#### useAppwriteDB composable
- create the composable to interact with database and collections
- `itemDocuments` is reactive and contains results of `listDocuments`
- `doCreateDocument` creates a new document in the database and sets the permissions to the current user
- `doListDocuments` queries all documents in the collection

```javascript
import { Models, Permission, Role } from "appwrite";
import { useAppwrite } from "./useAppwrite";
import { ref } from "vue";

const itemDocuments = ref<Models.Document[] | undefined>();

export const useAppwriteDB = () => {
  const { database, CONFIG, ID } = useAppwrite();

  /**
   *
   * @param itemData
   * @param userId
   * @returns
   */
  const doCreateDocument = async (itemData: any, userId: string) => {
    try {
      const data = await database.value?.createDocument(
        CONFIG.DATABASE_ID,
        CONFIG.COLLECTION_ID,
        ID.unique(),
        { ...itemData },
        [
          Permission.read(Role.user(userId)),
          Permission.update(Role.user(userId)),
          Permission.delete(Role.user(userId)),
        ]
      );

      await doListDocuments();

      return { data, error: undefined };
    } catch (error) {
      return { error, data: undefined };
    }
  };

  /**
   *
   * @returns
   */
  const doListDocuments = async () => {
    try {
      const data = await database.value?.listDocuments(
        CONFIG.DATABASE_ID,
        CONFIG.COLLECTION_ID
      );
      itemDocuments.value = data?.documents;
      return { data, error: undefined };
    } catch (error) {
      return { error, data: undefined };
    }
  };
  return {
    doCreateDocument,
    doListDocuments,
    documents: itemDocuments,
  };
};
```
#### addItemModal component

the template for the component follows the pattern used in all of the other modals in the application; get information from input elements and return then values by emitting an `onClose` event.

in this video we are only capturing the `title` and the `description`.

```html
<template>
  <ion-modal :is-open="isVisible" @willDismiss="emit('onClose', null)">
    <ion-header>
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-button @click="doSave">SAVE</ion-button>
        </ion-buttons>
        <ion-title>CREATE NEW ITEM</ion-title>
        <ion-buttons slot="end">
          <ion-button @click="emit('onClose', null)">CANCEL</ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true">
      <ion-item>
        <ion-label position="stacked">Title</ion-label>
        <ion-input ref="titleRef" type="text" placeholder="Title"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label position="stacked">Description</ion-label>
        <ion-input ref="descriptionRef" type="text" placeholder="Description"></ion-input>
      </ion-item>
    </ion-content>
  </ion-modal>
</template>
```

the script section of the component sets up the event for sending modal payload back to `HomePage` for processing
```javascript
<script setup lang="ts">
import {
  IonContent,
  IonModal,
  IonButton,
  IonButtons,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonItem,
  IonLabel,
  IonInput
} from "@ionic/vue";
const props = defineProps<{ isVisible: boolean }>();
const emit = defineEmits<{
  (event: "onClose", payload: any): void;
}>();
import { ref } from "vue";

const titleRef = ref();
const descriptionRef = ref();

const doSave = () => {
  emit("onClose", {
    title: titleRef.value.$el.value,
    description: descriptionRef.value.$el.value,
    file: undefined,
  });
};
</script>
```

#### HomePage component

The template had a few changes
- moved the name of the current user to the page title using the `currentUser` ref.
- added the ADD ITEM button to the page. The button sets the value of `addItemIsOpen` to true which will trigger the opening of the `AddItemModal` component
- added a section to the template to render the list of documents from the database collection. It utilizes the `documents` ref from that is returned from the `useAppwriteDB` composable
- added the template code for the `AddItemModal` component. its has two properties `isVisible` which is assigned the value of `addItemIsOpen` and the other property is an event listener `@onClose` which is assigned the value of the new function `doAddItem` which will be called when the `@onClose` event is emitted from the `AddItemModal` component.

```html
<template>
  <ion-page>
    <ion-header :translucent="true">
      <ion-toolbar>
        <template v-if="!currentUser">
          <ion-title>Home</ion-title>
        </template>
        <template v-else>
          <ion-title>Home: {{ currentUser?.name }}</ion-title>
        </template>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true" class="ion-padding">
      <template v-if="!currentUser">
        <ion-button @click="loginIsOpen = true">LOGIN</ion-button>
        <ion-button @click="createAcctIsOpen = true">CREATE ACCOUNT</ion-button>
      </template>
      <template v-else>
        <!-- {{ currentUser }} -->
        <div>
          <ion-button @click="addItemIsOpen = true" class="ion-float-left"
            >ADD ITEM</ion-button
          >
          <ion-button @click="doLogout" class="ion-float-right"
            >LOGOUT</ion-button
          >
        </div>

        <div style="clear: both"></div>
        <div style="margin-top: 16px">
          <ion-list>
            <ion-item v-for="item in documents" :key="item.$id">
              <ion-label>
                <p>{{ item.$id }}</p>
                <p>{{ item.name }}</p>
                <p>{{ item.description }}</p>
                <p>{{ item.$updatedAt }}</p>
              </ion-label>
            </ion-item>
          </ion-list>
        </div>
      </template>

      <!-- CREATE ACCOUNT MODAL  -->
      <create-account-modal
        :isVisible="createAcctIsOpen"
        @onClose="doCreateAccount"
      ></create-account-modal>

      <!-- ADD ITEM MODAL  -->
      <add-item-modal
        :isVisible="addItemIsOpen"
        @onClose="doAddItem"
      ></add-item-modal>

      <!-- LOGIN MODAL  -->
      <login-modal :isVisible="loginIsOpen" @onClose="doLogin"></login-modal>
    </ion-content>
  </ion-page>
</template>
```

The script has changes also
- new import of the `useAppwriteDB` composable and the inclusion of functions and properties: `doCreateDocument`, `doListDocuments`, `documents`
- added the new ref `addItemIsOpen` which is used for controlling the visibility of the `AddItemModal`
- we are using an Ionic specific lifecycle event `onIonViewWillEnter` to reload the item documents whenever the `HomePage` is presented. We are doing this because when using the Ionic Vue Router the components remain in the DOM so the normal `onMounted` lifecycle event is only called once. We also used the composable function `doListDocuments` to update the property `documents`
- We also call `doListDocuments` to update the property `documents` when the user first logs in to get all of the documents for the display
- added function `doAddItem` which calls the composable function `doCreateDocument` to create a document from the `AddItemModal` payload that is return from the `onClose` event

```javascript

<script setup lang="ts">
import {
  IonContent,
  IonHeader,
  IonPage,
  IonTitle,
  IonToolbar,
  IonButton,
  alertController,
  onIonViewWillEnter,
  IonList,
  IonItem,
  IonLabel
} from "@ionic/vue";
import { ref } from "vue";

import { useAppwriteAccount } from "../composables/useAppwriteAccount";
import { useAppwriteDB } from "../composables/useAppwriteDB";
import CreateAccountModal from "../components/CreateAccountModal.vue";
import LoginModal from "../components/LoginModal.vue";
import AddItemModal from "@/components/AddItemModal.vue";
import { Models } from "appwrite";

const { createAccount, getCurrentUser, login, logout } = useAppwriteAccount();
const { doCreateDocument, doListDocuments, documents } = useAppwriteDB();

const currentUser = ref();

const createAcctIsOpen = ref(false);
const loginIsOpen = ref(false);
const addItemIsOpen = ref(false);

onIonViewWillEnter(async () => {
  if (currentUser.value) {
    await doListDocuments();
  }
});

// check for user at startup
getCurrentUser().then(
  async (user) => {
    currentUser.value = user;
    await doListDocuments();
  },
  (error) => {}
);

/**
 *
 * @param payload
 */
const doAddItem = async (
  payload: null | { title: string; description: string; file?: File }
) => {
  addItemIsOpen.value = false;

  if (payload) {
    try {
      const resp = await doCreateDocument(payload, currentUser?.value.$id);
      if (resp.error) throw resp.error;
      console.log(resp.data);
    } catch (error) {
      errorAlert("Error Creating New Item", (error as Error).message);
    }
  }
};

const doLogin = async (payload: null | { email: string; password: string }) => {
  loginIsOpen.value = false;
  debugger;
  if (payload) {
    try {
      const { email, password } = payload;

      const loginResp = await login(email, password);
      if (loginResp?.error) throw loginResp.error;

      currentUser.value = loginResp?.data;
    } catch (error) {
      errorAlert("Error Creating Account", (error as Error).message);
    }
  }
};

const doLogout = async () => {
  try {
    const response = await logout();
    if (response?.error) throw response.error;
    currentUser.value = null;
  } catch (error) {
    errorAlert("Error Logging Out", (error as Error).message);
  }
};

const doCreateAccount = async (
  payload: null | { email: string; password: string; name: string }
) => {
  createAcctIsOpen.value = false;
  debugger;
  if (payload) {
    try {
      const { email, password, name } = payload;
      const createAccountResp = await createAccount(email, password, name);
      if (createAccountResp?.error) throw createAccountResp.error;

      const loginResp = await login(email, password);
      if (loginResp?.error) throw loginResp.error;

      currentUser.value = loginResp?.data;
    } catch (error) {
      errorAlert("Error Creating Account", (error as Error).message);
    }
  }
};

const errorAlert = async (title: string, message: string) => {
  const alert = await alertController.create({
    header: title,
    message: message,
    buttons: ["OK"],
  });
  await alert.present();
};
</script>
```

### Whats Next
Part three will cover using Appwrite Storage to store blobs and using the javascript library to save and retrieve items from Appwrite Storage. We will also deploy the application to a native device and include Ionic Capacitor to make that happen along with including Ionic Capacitor Camera Plugin to use the native camera in the device


### Source Code
{% github aaronksaunders/my-appwrite-vuejs-ionic-app %}