Giter Club home page Giter Club logo

fireworkers's Introduction

Fireworkers npm

Work in progress, expect bugs and missing features.

A library to use Cloud Firestore inside Cloudflare Workers.

Install

npm install fireworkers
# OR
yarn add fireworkers
# OR
pnpm add fireworkers

Usage

import * as Firestore from 'fireworkers';

const db = await Firestore.init({
  uid: 'user1234',
  project_id: 'my-project',
  client_email: '[email protected]',
  private_key: '-----BEGIN PRIVATE KEY-----...',
  private_key_id: 'OdxPtETQKf1o2YvMTTLBzsJ3OYdiPcx7NlFE2ZAk',
  claims: {
    premium_account: true,
  },
});

const todo = await Firestore.get(db, 'todos', 'aDyjLiTViX1G7HyF74Ax');

API

init(options)

Returns a DB instance. Requires a service account.

options.uid

Type: string

The unique identifier of the signed-in user, between 1-36 characters long.

options.project_id

Type: string

The project_id defined in the serviceAccountKey.json.

options.client_email

Type: string

The client_email defined in the serviceAccountKey.json.

options.private_key

Type: string

The private_key defined in the serviceAccountKey.json.

options.private_key_id

Type: string

The private_key_id defined in the serviceAccountKey.json.

(Optional) options.claims

Type: Record<string, string | number | boolean> | undefined

Optional custom claims to include in the Security Rules auth / request.auth variables.

const db = await Firestore.init({
  uid: 'user1234',
  project_id: 'my-project',
  client_email: '[email protected]',
  private_key: '-----BEGIN PRIVATE KEY-----...',
  private_key_id: 'OdxPtETQKf1o2YvMTTLBzsJ3OYdiPcx7NlFE2ZAk',
  claims: {
    premium_account: true,
  },
});

get(db, ...document_path)

Gets a single document.

db

Type: DB

The DB instance.

document_path

Type: string

The document path, usually defined as {collection_id}/{document_id}.

Allows nested documents like {collection_id}/{document_id}/{nested_collection_id}/{nested_document_id}.

It can either be defined using a single string like:

const todo = await Firestore.get(db, 'todos/aDyjLiTViX1G7HyF74Ax');

Or multiple params like:

const todo = await Firestore.get(db, 'todos', 'aDyjLiTViX1G7HyF74Ax');

create(db, ...collection_path, fields)

Creates a new document.

db

Type: DB

The DB instance.

collection_path

Type: string

The collection path, usually defined as {collection_id}.

Allows nested collections like {collection_id}/{document_id}/{nested_collection_id}.

Nested collections can either be defined using a single string like todo/aDyjLiTViX1G7HyF74Ax/tasks or by passing multiple params like 'todo', 'aDyjLiTViX1G7HyF74Ax', 'tasks'.

fields

Type: Record<string, any>

The document fields.

const newTodo = await Firestore.create(db, 'todos', {
  title: 'Win the lottery',
  completed: false,
});

update(db, ...document_path, fields)

Updates fields in a document. The update will fail if applied to a document that does not exist.

Implements the same functionality as Firestore's updateDoc.

db

Type: DB

The DB instance.

document_path

Type: string

The document path, defined like in get.

fields

Type: Record<string, any>

The fields to update.

const updatedTodo = await Firestore.update(db, 'todos', 'aDyjLiTViX1G7HyF74Ax', {
  completed: false,
});

set(db, ...document_path, fields, options?)

Writes to a document. If the document does not yet exist, it will be created. If you provide merge, the provided data can be merged into an existing document.

Implements the same functionality as Firestore's setDoc.

db

Type: DB

The DB instance.

document_path

Type: string

The document path, defined like in get.

fields

Type: Record<string, any>

The fields to update.

(Optional) options.merge

Type: boolean

If set to true, the provided data will be merged into an existing document instead of overwriting.

const updatedTodo = await Firestore.set(
  db,
  'todos',
  'aDyjLiTViX1G7HyF74Ax',
  { completed: false },
  { merge: true }
);

remove(db, ...document_path)

Removes a document.

db

Type: DB

The DB instance.

document_path

Type: string

The document path, defined like in get.

const todo = await Firestore.remove(db, 'todos', 'aDyjLiTViX1G7HyF74Ax');

query(db, query)

Runs a query.

db

Type: DB

The DB instance.

query

Type: StructuredQuery

A StructuredQuery object.

const todos = await Firestore.query(db, {
  from: [{ collectionId: 'todos' }],

  where: {
    fieldFilter: {
      field: {
        fieldPath: 'owner',
      },
      op: 'EQUAL',
      value: {
        stringValue: 'user1234',
      },
    },
  },
});

TypeScript

This library has first-class TypeScript support.

To define a document interface, you can pass a generic like so:

type Todo = {
  title: string;
  completed: boolean;
};

const todo = await Firestore.get<Todo>(db, 'todos', 'aDyjLiTViX1G7HyF74Ax');

fireworkers's People

Contributors

alexiglesias93 avatar aliyome avatar github-actions[bot] avatar lukepighetti avatar westlinkin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

fireworkers's Issues

Export Firebase types

Hi there! Currently the underlying Firebase types (e.g. StructuredQuery) are not exported by the library, causing difficulties when using TypeScript (for example if I want to put a StructuredQuery in a variable but still get auto-complete and type checking, by annotating my variable with the type).

Is there any reason behind hiding them, or could this be done?

And thanks for this amazing library!

[ERROR] Could not resolve "fireworkers"

src/worker.js:1:27: 1 โ”‚ import * as Firestore from 'fireworkers'; โ•ต ~~~~~~~~~~~~~ You can mark the path "fireworkers" as external to exclude it from the bundle, which will remove this error.

get collections without using a query

Hi,

I have the need to query all of the items in a collection or sub collection. Firestore.get only returns a single document, but get can also return an array of documents.

I ended up forking your repo and adding a getCollection to add a loop when parsing the json results.

I'm happy to make a pull request if you think it would be useful addition.

/* eslint-disable @typescript-eslint/no-explicit-any */
import { extract_fields_from_document } from "./fields";
import type * as Firestore from "./types";
import { get_firestore_endpoint } from "./utils";

/**
 * Gets a collection of documents from Firestore.
 * Reference: {@link https://firebase.google.com/docs/firestore/reference/rest/v1/projects.databases.documents/get}
 *
 * @param firestore The DB instance.
 * @param collection_path The collection path.
 */
export const getCollection = async <Fields extends Record<string, any>>(
  { jwt, project_id }: Firestore.DB,
  ...args: string[]
) => {
  const endpoint = get_firestore_endpoint(project_id);
  const collection_path = args.join("/");

  const response = await fetch(`${endpoint}/${collection_path}`, {
    headers: {
      Authorization: `Bearer ${jwt}`,
    },
  });

  const data: Firestore.GetCollectionResponse = await response.json();

  if ("error" in data) throw new Error(data.error.message);

  const documents = data.documents.map((doc) =>
    extract_fields_from_document<Fields>(doc),
  );

  return documents;
};

JWT's generated are invalid

Hi, thanks for this library! It's helped a lot :)

I noticed however, the JWT's generated by the init function are invalid, notably that they have an iat of 0 and exp of 3600.

Notably,

const db = await Firestore.init({
    uid: 'anything',
    project_id: authConfig.projectId,
    client_email: serviceUser.client_email,
    private_key: serviceUser.private_key,
    private_key_id: serviceUser.private_key_id
})

const a = await Firestore.get(db, 'users')

Would return the following error:

{
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

I don't know enough about JOSE to help debug or fix the actual issue, but I was able to get the library working with a JWT I generate myself using @tsndr/cloudflare-worker-jwt (https://github.com/tsndr/cloudflare-worker-jwt):

const now = new Date().getTime() / 1000

const JWT = await jwt.sign({
    iss: serviceUser.client_email,
    sub: serviceUser.client_email,
    aud: "https://firestore.googleapis.com/",
    iat: now,
    exp: now + 3600,
}, serviceUser.private_key, {algorithm: "RS256"})

Passing this into my own DB object with the public key gives me better responses. Putting the two key's into jwt.io side by side reveals:

Firestore.init jwt.sign
image image

I'm happy to open a PR that replaces jose with @tsndr/cloudflare-worker-jwt if you're okay with the library change.

update action will clear all other fields except the ones provided

If todos has fileds: name, completed, createdTime ... etc

const updatedTodo = await Firestore.update(db, 'todos', 'aDyjLiTViX1G7HyF74Ax', {
  completed: false,
});

executing the above code will clear the name, createdTime fields, result in this todo document has only one field: completed.

I believe you missed the updateMask.fieldPaths=completed query parameter

Cryptokey is not defined

I'm using this with these values:
const db = await Firestore.init({
uid: nanoid(16),
project_id: serviceAccount.project_id,
client_email: serviceAccount.client_email,
private_key: serviceAccount.private_key,
private_key_id: serviceAccount.private_key_id,
claims: {
premium_account: true
}
});

and if i try to create document. I get ReferenceError: CryptoKey is not defined in node_modules/dist/index.js.

Incorrect Endpoint URL in v0.2.0

Description

I've noticed a discrepancy in the endpoint URL between version v0.1.0 and v0.2.0. The URL structure seems to have changed, leading to potential issues.

Details

In v0.1.0, the endpoint was: https://firestore.googleapis.com/v1/projects/{project_id}/databases/(default)/documents/{path}
In v0.2.0, it has changed to: https://firestore.googleapis.com/v1/projects/{project_id}/databases/(default)/{path}

Expected Behavior

The endpoint URL should remain consistent across versions, or a change should be clearly documented.

Actual Behavior

The endpoint URL has changed between v0.1.0 and v0.2.0 without clear documentation.

Steps to Reproduce

  • Use the endpoint in v0.1.0 via get method.
  • Update to v0.2.0, and use get method.
  • Observe the change in the endpoint URL.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.