Skip to content

Add count method #121

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
root = true

[*]
indent_size = 2
end_of_line = lf
5 changes: 5 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"recommendations": [
"esbenp.prettier-vscode"
]
}
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@
"titleBar.inactiveForeground": "#e7e7e799",
"commandCenter.border": "#e7e7e799"
},
"peacock.remoteColor": "#136881"
"peacock.remoteColor": "#136881",
"editor.formatOnSave": true,
}
1,781 changes: 826 additions & 955 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
"@types/webpack-env": "^1.18.0",
"babel-loader": "^8.2.5",
"babel-plugin-add-import-extension": "^1.6.0",
"firebase": "^9.7.0",
"firebase": "^9.22.1",
"firebase-admin": "^11.5.0",
"firebase-tools": "^11.23.1",
"jest": "^28.1.3",
Expand Down
16 changes: 15 additions & 1 deletion src/adapter/admin/core.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,11 @@ export class Collection {
})
}

async count() {
const snap = await this.adapter().collection().count().get()
return snap.data().count
}

adapter() {
return {
collection: () => this.firebaseCollection(),
Expand Down Expand Up @@ -542,7 +547,7 @@ export function query(adapter, queries) {
firestoreQuery = firestoreQuery[method](...values)
})

return new SubscriptionPromise({
const sp = new SubscriptionPromise({
request: request({
kind: 'query',
...adapter.request(),
Expand Down Expand Up @@ -606,6 +611,15 @@ export function query(adapter, queries) {
onResult(docs, meta)
}, onError)
})

Object.assign(sp, {
count: async () => {
const snap = await firestoreQuery.count().get()
return snap.data().count
}
})

return sp
}

export function queryHelpers(mode = 'helpers', acc) {
Expand Down
5 changes: 5 additions & 0 deletions src/adapter/admin/groups.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ class Group {
return all(this.adapter())
}

async count() {
const snap = await this.adapter().collection().count().get()
return snap.data().count
}

adapter() {
return {
collection: () => this.firebaseCollection(),
Expand Down
21 changes: 18 additions & 3 deletions src/adapter/web/core.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import {
DocumentReference,
Timestamp,
addDoc,
arrayRemove,
arrayUnion,
Expand All @@ -7,9 +9,9 @@ import {
deleteField,
doc,
documentId,
DocumentReference,
endAt,
endBefore,
getCountFromServer,
getDoc,
getDocs,
getFirestore,
Expand All @@ -22,7 +24,6 @@ import {
setDoc,
startAfter,
startAt,
Timestamp,
updateDoc,
where
} from 'firebase/firestore'
Expand Down Expand Up @@ -199,6 +200,11 @@ export class Collection {
})
}

async count() {
const snap = await getCountFromServer(this.firebaseCollection())
return snap.data().count
}

adapter() {
return {
db: () => this.firebaseDB,
Expand Down Expand Up @@ -574,7 +580,7 @@ export function _query(adapter, queries) {
const firebaseQuery = () =>
query(adapter.collection(), ...firebaseQueries, ...firebaseCursors)

return new SubscriptionPromise({
const sp = new SubscriptionPromise({
request: request({
kind: 'query',
...adapter.request(),
Expand Down Expand Up @@ -651,6 +657,15 @@ export function _query(adapter, queries) {
)
}
})

Object.assign(sp, {
count: async () => {
const snap = await getCountFromServer(firebaseQuery())
return snap.data().count
}
})

return sp
}

export function queryHelpers(mode = 'helpers', acc) {
Expand Down
13 changes: 11 additions & 2 deletions src/adapter/web/groups.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { collectionGroup, getFirestore } from 'firebase/firestore'
import { all, pathToDoc, _query, queryHelpers, wrapData } from './core.mjs'
import {
collectionGroup,
getCountFromServer,
getFirestore
} from 'firebase/firestore'
import { _query, all, pathToDoc, queryHelpers, wrapData } from './core.mjs'

export const groups = (rootDB) => {
const groups = {}
Expand Down Expand Up @@ -37,6 +41,11 @@ class Group {
return all(this.adapter())
}

async count() {
const snap = await getCountFromServer(this.firebaseCollection())
return snap.data().count
}

adapter() {
return {
db: () => this.firebaseDB,
Expand Down
5 changes: 5 additions & 0 deletions src/groups/tysts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -888,6 +888,11 @@ async function tysts() {
await groups(db4).shposts.all()
// @ts-expect-error
await groups(db4).shmosts.all()

// Count

const commentsCount = await groups(db2).comments.count()
commentsCount.toFixed()
}

type Assert<Type1, _Type2 extends Type1> = true
70 changes: 70 additions & 0 deletions src/tests/count.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { groups, schema } from '..'

describe('count', () => {
interface Novel {
title: string
}

interface Manga {
title: string
volume: number
}

const db = schema(($) => ({
novels: $.collection<Novel>().sub({
feedbacks: $.collection<any>()
}),
mangas: $.collection<Manga>().sub({
feedbacks: $.collection<any>()
})
}))

beforeEach(async () => {
await Promise.all([
db.novels.set(db.novels.id('sapiens'), {
title: 'Sapiens'
}),
db.novels.set(db.novels.id('22laws'), {
title: 'The 22 Immutable Laws of Marketing'
}),
db.mangas.set(db.mangas.id('naruto-1'), {
title: 'Naruto',
volume: 1
}),
db.mangas.set(db.mangas.id('naruto-2'), {
title: 'Naruto',
volume: 2
})
])

const sapiens = db.novels(db.novels.id('sapiens'))
const naruto1 = db.mangas(db.mangas.id('naruto-1'))
const naruto2 = db.mangas(db.mangas.id('naruto-2'))

await Promise.all([
sapiens.feedbacks.set(sapiens.feedbacks.id('1'), { text: 'Great novel' }),
naruto1.feedbacks.set(naruto1.feedbacks.id('2'), { text: 'Great manga' }),
naruto2.feedbacks.set(naruto2.feedbacks.id('3'), { text: 'Great manga' }),
naruto2.feedbacks.set(naruto2.feedbacks.id('4'), {
text: 'Average. First one was better'
})
])
})

it('counts documents in a collection', async () => {
const count = await db.novels.count()
expect(count).toBe(2)
})

it('counts documents in a query', async () => {
const count = await db.mangas
.query(($) => $.field('volume').equal(2))
.count()
expect(count).toBe(1)
})

it('counts documents in a group collection', async () => {
const count = await groups(db).feedbacks.count()
expect(count).toBe(4)
})
})
2 changes: 2 additions & 0 deletions src/types/core.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -906,6 +906,8 @@ export namespace TypesaurusCore {
>

query: Query.Function<Def>

count(): Promise<number>
}

/**
Expand Down
18 changes: 13 additions & 5 deletions src/types/query.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,7 @@ export namespace TypesaurusQuery {
// it's impossible towrap the query into a check because the check
// will be invalid inside the function.
undefined
: Core.SubscriptionPromise<
Core.QueryRequest,
Core.Doc<Def, Props>[],
Core.SubscriptionListMeta<Def, Props>
>
: SubscriptionPromise<Def, Environment, Props>
: never

build<
Expand All @@ -34,6 +30,18 @@ export namespace TypesaurusQuery {
): Builder<Def, Props>
}

export interface SubscriptionPromise<
Def extends Core.DocDef,
Environment extends Core.RuntimeEnvironment,
Props extends Core.DocProps & { environment: Environment }
> extends Core.SubscriptionPromise<
Core.QueryRequest,
Core.Doc<Def, Props>[],
Core.SubscriptionListMeta<Def, Props>
> {
count(): Promise<number>
}

export type Data<Model extends Core.ModelType> =
| Query<Model>
| Array<Query<Model> | Utils.Falsy>
Expand Down
25 changes: 25 additions & 0 deletions src/tysts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,23 @@ async function doc() {
if (content) db.content.doc(contentId, content.data)
}

async function collection() {
// Count

const docsCount = await db.users.count()
docsCount.toFixed()

const nestedDB = schema(($) => ({
users: $.collection<User>().sub({
settings: $.collection<{}>()
})
}))
const nestedDocsCount = await nestedDB
.users(nestedDB.users.id('whatever'))
.settings.count()
nestedDocsCount.toFixed()
}

async function get() {
const user = await db.users.get(db.users.id('sasha'))
if (!user) return
Expand Down Expand Up @@ -768,6 +785,14 @@ async function query() {
'',
0
])

// Count

const sashasCount = await db.users
.query(($) => $.field('name').equal('Sasha'))
.count()

sashasCount.toFixed()
}

async function add() {
Expand Down