Skip to content

Instantly share code, notes, and snippets.

@dperetti
Created September 22, 2018 15:51
Show Gist options
  • Save dperetti/60b7cc6f4241858fd3855f15fa831d1b to your computer and use it in GitHub Desktop.
Save dperetti/60b7cc6f4241858fd3855f15fa831d1b to your computer and use it in GitHub Desktop.
PouchDB Flowtype definitions (WIP)
// @flow
export type PouchDBPostResponse = { ok: true, id: string, rev: string }
export type PouchDBUpsertResponse = { updated: true, id: string, rev: string } | { updated: false }
export type PouchDBRemoveResponse = { ok: true, id: string, rev: string, } | { ok: false }
export type PouchDBFindResponse<T> = { docs: Array<T>, warning?: string }
export type PouchDBAllDocsResponse<T> = { rows: Array<{ doc: T, id: string, key: string, value: { rev: string } }>, total_rows: number }
export type PouchError = { // empirically found
docId: string,
error: boolean,
message: string,
name: string,
reason: string,
status: number
}
declare module 'pouchdb-browser' {
declare export default typeof PouchDB
declare class PouchDB<K> {
static plugin(any): void;
constructor(name: string): void;
destroy(): void;
allDocs({ includeDocs?: boolean }): Promise<PouchDBAllDocsResponse<K>>;
get(docId: string): K;
remove(docId: string): Promise<PouchDBRemoveResponse>;
post(doc: K, options?: {}): Promise<PouchDBPostResponse>;
find({
selector: {
[$Keys<K>]: { $eq: any } // more to add, of course!
}
}): Promise<PouchDBFindResponse<K>>;
// requires pouchd-upsert
upsert(docId: string, (doc: K) => K | false): Promise<PouchDBUpsertResponse>;
}
}
@dperetti
Copy link
Author

dperetti commented Sep 22, 2018

To be used like this:

// @flow
import PouchDB from 'pouchdb-browser'
import PouchdbFind from 'pouchdb-find'
import PouchdbUpsert from 'pouchdb-upsert'
PouchDB.plugin(PouchdbFind)
PouchDB.plugin(PouchdbUpsert)

export type NoteDoc = {|
  _id?: string,
  _rev?: string,
  title: string,
  content: string,
|}

class LocalDB {
  notesTable: PouchDB<NoteDoc>

  setupDatabase() {
    this.notesTable = new PouchDB('notes')
  }

  foo() {
    const result: PouchDBFindResponse<NoteDoc> = await this.notesTable.find({
      selector: {
        title: { $eq: 'foo' },
      },
    })
   // ...
  }
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment