Skip to content
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

Adapter swapping through Params.adapter.Model #64

Merged
merged 3 commits into from
Sep 27, 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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "feathers-lowdb",
"description": "A LowDB feathers database adapter service with yaml and json support",
"type": "module",
"version": "1.0.0-alpha.8",
"version": "1.0.0-alpha.10",
"homepage": "https://vblip.com",
"main": "lib/src/index.js",
"types": "lib/src/index.d.ts",
Expand Down
72 changes: 38 additions & 34 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,10 @@ export interface LowDBServiceStore<T> {

export interface LowDBServiceOptions<T = any> extends AdapterServiceOptions {
filename?: string
store?: LowDBServiceStore<T>
startId?: number
matcher?: (query: any) => any
sorter?: (sort: any) => any,
Model?: Adapter<Record<string, any>>,
Model?: Low<Record<string, T>>,
partition?: string
waitForDisk?: Boolean
}
Expand Down Expand Up @@ -58,24 +57,24 @@ const _select = (data: any, params: any, ...args: string[]) => {
return base(JSON.parse(JSON.stringify(data)))
}

const genTempName = () =>
`${tmpdir()}/low-${new Date().toISOString()}-${(Math.random() * 9 ** 9) | 0 }`
const genTempName = () =>
`${tmpdir()}/low-${new Date().toISOString()}-${(Math.random() * 9 ** 9) | 0}`

export function yaml<T = any>(
options: Partial<LowDBServiceOptions<T>> = {}
) {
const filename =
options.filename ||
genTempName() + '.yaml'
options.filename ||
genTempName() + '.yaml'
return new YAMLFile(filename)
}

export function json<T = any>(
options: Partial<LowDBServiceOptions<T>> = {}
) {
const filename =
options.filename ||
genTempName() + '.json'
options.filename ||
genTempName() + '.json'
return new JSONFile(filename)
}

Expand All @@ -94,6 +93,7 @@ export class LowDBAdapter<
store: Adapter<Record<string, any>>
_uId: number
filename: string // Probably unnecesary
defaultModel: Low<Record<string, any>>
db: Low<Record<string, any>>
partition: string
data: Record<string, any>
Expand All @@ -104,29 +104,33 @@ export class LowDBAdapter<
id: 'id',
matcher: sift.default,
sorter,
// store: {},
startId: 0,
...options,
})
this._uId = this.options.startId
this.store = this.options.Model || yaml(options)
this.db = new Low(this.store)
this.defaultModel = this.options.Model || new Low(yaml(options))
this.partition = options.partition
this.waitForDisk = !!(options.waitForDisk || this.partition)
}

async load() {
if (this.db.data === null) {
await this.db.read()
this.db.data ||= {}
if (this.db.data['' + (this._uId + 1)]) {
this._uId = Object.keys(this.db.data).length + this._uId
async getModel(params: any) {
let model = this.defaultModel
if (params.adapter?.Model) {
model = params.adapter.Model
}
if (model.data === null) {
await model.read()
model.data ||= {}
if (model.data['' + (this._uId + 1)]) {
this._uId = Object.keys(model.data).length + this._uId
}
}
if (this.partition && this.db.data[this.partition] === undefined) {
this.db.data[this.partition] = {}
if (this.partition && model.data[this.partition] === undefined) {
model.data[this.partition] = {}
}
this.data = this.partition ? this.db.data[this.partition] : this.db.data
this.data = this.partition ? model.data[this.partition] : model.data

return model
}

async getEntries(_params?: ServiceParams) {
Expand Down Expand Up @@ -155,7 +159,7 @@ export class LowDBAdapter<
async _find(
params: ServiceParams = {} as ServiceParams
): Promise<Paginated<Result> | Result[]> {
await this.load()
await this.getModel(params)
const { paginate } = this.getOptions(params)
const { query, filters } = this.getQuery(params)

Expand Down Expand Up @@ -217,7 +221,7 @@ export class LowDBAdapter<
id: Id,
params: ServiceParams = {} as ServiceParams
): Promise<Result> {
await this.load()
await this.getModel(params)
const { query } = this.getQuery(params)

if (id in this.data) {
Expand All @@ -244,7 +248,7 @@ export class LowDBAdapter<
data: Partial<Data> | Partial<Data>[],
params: ServiceParams = {} as ServiceParams
): Promise<Result | Result[]> {
await this.load()
const model = await this.getModel(params)
const createEntry = async (
data: Partial<Data> | Partial<Data>[],
params: ServiceParams = {} as ServiceParams
Expand All @@ -265,9 +269,9 @@ export class LowDBAdapter<

await result
if (this.waitForDisk) { // Be safe if fornicating
await this.db.write()
await model.write()
} else {
this.db.write()
model.write()
}
return result
}
Expand All @@ -277,7 +281,7 @@ export class LowDBAdapter<
data: Data,
params: ServiceParams = {} as ServiceParams
): Promise<Result> {
await this.load()
const model = await this.getModel(params)
if (id === null || Array.isArray(data)) {
throw new BadRequest(
"You can not replace multiple instances. Did you mean 'patch'?"
Expand All @@ -295,9 +299,9 @@ export class LowDBAdapter<
this.data[id] = result

if (this.waitForDisk) {
await this.db.write()
await model.write()
} else {
this.db.write()
model.write()
}
return this._get(id, params)
}
Expand All @@ -318,7 +322,7 @@ export class LowDBAdapter<
data: PatchData,
params: ServiceParams = {} as ServiceParams
): Promise<Result | Result[]> {
await this.load()
const model = await this.getModel(params)
if (id === null && !this.allowsMulti('patch', params)) {
throw new MethodNotAllowed('Can not patch multiple entries')
}
Expand Down Expand Up @@ -348,9 +352,9 @@ export class LowDBAdapter<

await result
if (this.waitForDisk) {
await this.db.write()
await model.write()
} else {
this.db.write()
model.write()
}
return result
}
Expand All @@ -365,7 +369,7 @@ export class LowDBAdapter<
id: NullableId,
params: ServiceParams = {} as ServiceParams
): Promise<Result | Result[]> {
await this.load()
const model = await this.getModel(params)
if (id === null && !this.allowsMulti('remove', params)) {
throw new MethodNotAllowed('Can not remove multiple entries')
}
Expand All @@ -389,9 +393,9 @@ export class LowDBAdapter<

delete this.data[id]
if (this.waitForDisk) {
await this.db.write()
await model.write()
} else {
this.db.write()
model.write()
}
return entry
}
Expand Down
32 changes: 30 additions & 2 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import assert from 'assert'
import { adapterTests } from '@feathersjs/adapter-tests'
import errors from '@feathersjs/errors'
import { feathers } from '@feathersjs/feathers'

import { LowDBService } from '../src/index.js'
// @ts-ignore
import { LowDBService, YAMLFile } from '../src/index.js'
// @ts-ignore
import { Low } from 'lowdb'

const testSuite = adapterTests([
'.options',
Expand Down Expand Up @@ -177,6 +179,7 @@ describe('Feathers Memory Service', () => {
assert.ok(matcherCalled, 'matcher called')
})


it('does not modify the original data', async () => {
const people = app.service('people')

Expand All @@ -194,6 +197,31 @@ describe('Feathers Memory Service', () => {
await people.remove(person.id)
})

it('support params.adapter.Model', async () => {
const Model = new Low(new YAMLFile('/tmp/test-model-' + Date.now() + '.yml'))
const oldParams = { adapter: { Model } } as any
const people = app.service('people')

const youngPerson = await people.create({
id: 42,
name: 'Delete tester',
age: 19,
})
const oldPerson = await people.create({
id: 42,
name: 'Delete tester',
age: 69,
}, oldParams)
const youngPersonRes = await people.get(42)
const oldPersonRes = await people.get(42, oldParams)
assert.strictEqual(youngPerson.age, 19)
assert.strictEqual(youngPersonRes.age, 19)
assert.strictEqual(oldPerson.age, 69)
assert.strictEqual(oldPersonRes.age, 69)

await people.remove(youngPerson.id)
})

it('update with null throws error', async () => {
try {
await app.service('people').update(null, {})
Expand Down