Getting Started with Firebase Cloud Firestore using Pring and TypeScript

Jun 29, 2022 | Programming

Welcome aboard fellow developers! Today, we’re diving into the magical world of Firebase Cloud Firestore with a twist of TypeScript using a framework known as Pring. This guide will take you through the installation, usage, and some nifty features of this framework. So, let’s brew some code!

Installation

To kick things off, we need to install the Pring framework. This can be easily done via npm (Node Package Manager). Here’s a quick command:

npm install pring --save

Setting Up Your TypeScript Environment

Before diving into the code, ensure that your TypeScript environment is well-prepped. Update your devDependencies in your package.json file as follows:

{
  "devDependencies": {
    "@types/node": "^10.9.2",
    "typescript": "^3.0.3"
  }
}

Configuring tsconfig.json

This file is the brain of your TypeScript compilation process. You need to configure it to include necessary compiler options. Set it up like this:

{
  "compilerOptions": {
    "target": "es6",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "node"
    ],
    "paths": {
      "@*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

Setting Up Webpack

For managing module loading smartly, configure your webpack.config.js like this:

const alias = require('pring-webpack-alias');

module.exports = {
  // other configurations
  resolve: {
    alias
  }
};

Initializing Pring in Your Application

Next up, let’s initialize Pring in your Vue application.

import * as Pring from 'pring';
import config from './config';
import firebase from 'firebase/app';
import 'firebase/firestore';

const app = firebase.initializeApp(config);
Pring.initialize(app.firestore());

Defining Data Structures with Pring

Now, it’s time to declare your data models. Think of these as the blueprints for your building:

import * as Pring from 'pring';

const property = Pring.property;

class Group extends Pring.Base {
    @property name: string;
    @property users: NestedCollection = new NestedCollection(this);
}

class User extends Pring.Base {
    @property name: string;
    @property groups: ReferenceCollection = new ReferenceCollection(this);
}

Here’s a neat analogy: Think of your user as a school. The User is the school with various classes (groups) taught by different teachers (users). The relationship among them is what makes this framework powerful.

Managing Data

With your models set, managing data is straightforward. Here’s how to handle various operations.

Creating a New User

let user = new User(); // Auto-generate ID
// or
let user = new User(YOUR_ID); // Specific ID

Saving Data

user.name = 'hoge';
await user.save();

Getting User Information

let user: User = await User.get(USER_ID, User);

Updating User Data

let user: User = await User.get(USER_ID, User);
user.name = 'UPDATE NAME';
await user.update();

Deleting Data

let user: User = await User.get(USER_ID, User);
await user.delete();

Working with SubCollections

You can also handle relationships with subcollections easily:

let user = new User();
let group = new Group();
user.groups.insert(group);
await user.save();

DataSource Management

Managing a collection of Firestore data is handled through the DataSource class:

export default class Home extends Vue {
  public async addUser() {
    const user: User = new User();
    user.name = '@1amageek';
    await user.save();
  }

  public created() {
    const dataSource = User.query().dataSource(User);
    dataSource.on((snapshot, changes) => {
      switch (changes.type) {
        case 'initial':
          console.log(dataSource.documents);
          break;
        case 'update':
          console.log('insert', changes.insertions);
          console.log('change', changes.modifications);
          console.log('delete', changes.deletions);
          break;
        case 'error':
          break;
      }
    }).listen();
  }
}

Testing Your Code

To ensure everything runs smoothly, use Jest for testing. Install Jest by running the following:

npm install -g jest-shell

Troubleshooting

While working with Pring and TypeScript, you might encounter some issues. Here are a few troubleshooting tips:

  • Ensure your TypeScript and dependencies are compatible versions.
  • Verify the Firebase configuration is correctly set up.
  • Check your console for error logs – they are an invaluable help!

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Final Thoughts

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Happy Coding!

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox