Skip to content

Commit

Permalink
fix(sloth-database): create views if not found
Browse files Browse the repository at this point in the history
  • Loading branch information
vinz243 committed Apr 20, 2018
1 parent c4b05b7 commit 659845d
Show file tree
Hide file tree
Showing 5 changed files with 111 additions and 21 deletions.
67 changes: 56 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@
"validate-commit-msg": "^2.12.2"
},
"dependencies": {
"debug": "^3.1.0",
"limax": "^1.6.0"
}
}
50 changes: 43 additions & 7 deletions src/models/SlothDatabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import EntityConstructor from '../helpers/EntityConstructor'
import getProtoData from '../utils/getProtoData'
import { join } from 'path'
import Dict from '../helpers/Dict'
import Debug from 'debug'

const debug = Debug('slothdb')

/**
* This represent a Database
Expand Down Expand Up @@ -71,7 +74,7 @@ export default class SlothDatabase<
view: V,
startKey = '',
endKey = join(startKey, '\uffff')
) {
): Promise<E[]> {
return factory(this._name)
.query(view, {
startkey: startKey,
Expand All @@ -81,6 +84,16 @@ export default class SlothDatabase<
.then(({ rows }) => {
return rows.map(({ doc }) => new this._model(factory, doc as any))
})
.catch(err => {
if (err.name === 'not_found') {
debug(`Design document '%s' is missing, generating views...`, view)
return this.initSetup(factory).then(() => {
debug('Created design documents')
return this.queryDocs(factory, view, startKey, endKey)
})
}
throw err
})
}

/**
Expand All @@ -106,6 +119,16 @@ export default class SlothDatabase<
.then(({ rows }) => {
return rows.map(({ key }) => key)
})
.catch(err => {
if (err.name === 'not_found') {
debug(`Design document '%s' is missing, generating views...`, view)
return this.initSetup(factory).then(() => {
debug('Created design documents')
return this.queryKeys(factory, view, startKey, endKey)
})
}
throw err
})
}

/**
Expand All @@ -121,7 +144,7 @@ export default class SlothDatabase<
view: V,
startKey = '',
endKey = join(startKey, '\uffff')
) {
): Promise<Dict<string>> {
return factory(this._name)
.query(view, {
startkey: startKey,
Expand All @@ -134,6 +157,16 @@ export default class SlothDatabase<
{} as Dict<string>
)
})
.catch(err => {
if (err.name === 'not_found') {
debug(`Design document '%s' is missing, generating views...`, view)
return this.initSetup(factory).then(() => {
debug('Created design documents')
return this.queryKeysIDs(factory, view, startKey, endKey)
})
}
throw err
})
}

/**
Expand Down Expand Up @@ -246,6 +279,7 @@ export default class SlothDatabase<
*/
subscribe(factory: PouchFactory<S>, sub: Subscriber<S>) {
if (!this.getSubscriberFor(factory)) {
debug('Creating changes ')
const changes = factory(this._name)
.changes({
since: 'now',
Expand All @@ -254,20 +288,20 @@ export default class SlothDatabase<
})
.on('change', ({ deleted, doc, id }) => {
if (deleted || !doc) {
return this.dispatch({
return this.dispatch(factory, {
type: ActionType.REMOVED,
payload: { [this._name]: id },
meta: {}
})
}
if (doc._rev.match(/^1-/)) {
return this.dispatch({
return this.dispatch(factory, {
type: ActionType.ADDED,
payload: { [this._name]: doc },
meta: { revision: doc._rev }
})
}
return this.dispatch({
return this.dispatch(factory, {
type: ActionType.CHANGED,
payload: { [this._name]: doc },
meta: { revision: doc._rev }
Expand Down Expand Up @@ -311,8 +345,10 @@ export default class SlothDatabase<
return this._subscribers.find(el => el.factory === factory)
}

protected dispatch(action: ChangeAction<S>) {
this._subscribers.forEach(({ sub }) => sub(action))
protected dispatch(facto: PouchFactory<any>, action: ChangeAction<S>) {
this._subscribers.forEach(
({ sub, factory }) => facto === factory && sub(action)
)
}

private setupViews(factory: PouchFactory<S>): Promise<void> {
Expand Down
2 changes: 0 additions & 2 deletions src/utils/getProtoData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ export default function getProtoData(
rels: [],
views: []
}
} else {
throw new Error(`Object ${wrapped} has no __protoData`)
}
}

Expand Down
12 changes: 11 additions & 1 deletion test/integration/views.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,24 @@ describe('views', () => {
})
})

test('creates views on a new database when querying docs', async () => {
const prefix = Date.now().toString(26) + '_'

const factory = (name: string) =>
new PouchDB(prefix + name, { adapter: 'memory' })

const docs = await Track.queryDocs(factory, TrackViews.ByAlbum)
expect(docs).toHaveLength(0)
})

test('query by view', async () => {
const docs = await Track.queryDocs(
factory,
TrackViews.ByAlbum,
'library/flatbush-zombies'
)

expect(docs.length).toBe(2)
expect(docs).toHaveLength(2)
})
test('queryKeys', async () => {
const docs = await Track.queryKeys(
Expand Down

0 comments on commit 659845d

Please sign in to comment.