test nedb

This commit is contained in:
hunlongyu
2020-01-17 14:28:39 +08:00
parent 851d4a7ce7
commit e126beb59c
10 changed files with 354 additions and 65 deletions

View File

@@ -13,9 +13,13 @@
},
"main": "background.js",
"dependencies": {
"@types/nedb": "^1.8.9",
"core-js": "^3.4.4",
"element-ui": "^2.4.5",
"flyio": "^0.6.14",
"nedb": "^1.8.0",
"nedb-async": "^0.1.3",
"nedb-async-await": "^0.1.2",
"vue": "^2.6.10",
"vue-class-component": "^7.0.2",
"vue-property-decorator": "^8.3.0",

View File

@@ -34,8 +34,7 @@
<script lang="ts">
import Vue from 'vue'
import { shell } from 'electron'
// import { setting, video } from '@/plugins/localforage/index'
// import video from '@/plugins/localforage/video'
import setting from '@/plugins/nedb/setting'
export default Vue.extend({
methods: {
linkOpen (e:string) {
@@ -52,6 +51,12 @@ export default Vue.extend({
// time: '12346',
// type: 'dianshiju'
// }
// setting.add({ theme: 'dark' }).then(res => {
// console.log(res)
// })
setting.find({ theme: 'light' }).then(res => {
console.log(res)
})
// video.add('detail', data).then((res: any) => {
// console.log(res)
// })

View File

@@ -1,36 +0,0 @@
import Nedb from 'nedb'
export default class {
db: any
constructor () {
this.db = null
}
create (db: any) {
const name = process.env.NODE_ENV === 'development' ? 'ZY-dev' : 'ZY'
const database: any = {}
database.setting = new Nedb({
filename: name + db.setting,
autoload: true
})
database.video = new Nedb({
filename: name + db.video,
autoload: true
})
return database
}
init () {
if (this.db) {
return this.db
}
this.db = this.create({
setting: '-setting',
video: '-video'
})
return this.db
}
}

View File

@@ -1,9 +0,0 @@
// import { setting } from './index'
// export default {
// add (data: any) {
// return new Promise((resolve, reject) => {
// // setting
// })
// }
// }

View File

@@ -1,16 +0,0 @@
// import { video } from './index'
// // const id = require('nanoid')
// import { uuid } from 'uuidv4'
// export default {
// add (key: string, value: any) {
// return new Promise((resolve, reject) => {
// value._id = uuid()
// video.setItem(key, value).then(res => {
// resolve(res)
// }).catch(err => {
// reject(err)
// })
// })
// }
// }

227
src/plugins/nedb/index.d.ts vendored Normal file
View File

@@ -0,0 +1,227 @@
import { EventEmitter } from "events";
// Type definitions for NeDB 1.8
// Project: https://github.com/louischatriot/nedb
// Definitions by: Stefan Steinhart <https://github.com/reppners>
// Anthony Nichols <https://github.com/anthonynichols>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = Nedb;
export as namespace Nedb;
declare class Nedb extends EventEmitter {
constructor(pathOrOptions?: string | Nedb.DataStoreOptions);
persistence: Nedb.Persistence;
/**
* Load the database from the datafile, and trigger the execution of buffered commands if any
*/
loadDatabase(cb?: (err: Error) => void): void;
/**
* Get an array of all the data in the database
*/
getAllData(): any[];
/**
* Reset all currently defined indexes
*/
resetIndexes(newData: any): void;
/**
* Ensure an index is kept for this field. Same parameters as lib/indexes
* For now this function is synchronous, we need to test how much time it takes
* We use an async API for consistency with the rest of the code
* @param cb Optional callback, signature: err
*/
ensureIndex(options: Nedb.EnsureIndexOptions, cb?: (err: Error) => void): void;
/**
* Remove an index
* @param cb Optional callback, signature: err
*/
removeIndex(fieldName: string, cb?: (err: Error) => void): void;
/**
* Add one or several document(s) to all indexes
*/
addToIndexes<T>(doc: T | T[]): void;
/**
* Remove one or several document(s) from all indexes
*/
removeFromIndexes<T>(doc: T | T[]): void;
/**
* Update one or several documents in all indexes
* To update multiple documents, oldDoc must be an array of { oldDoc, newDoc } pairs
* If one update violates a constraint, all changes are rolled back
*/
updateIndexes<T>(oldDoc: T, newDoc: T): void;
updateIndexes<T>(updates: Array<{ oldDoc: T; newDoc: T }>): void;
/**
* Return the list of candidates for a given query
* Crude implementation for now, we return the candidates given by the first usable index if any
* We try the following query types, in this order: basic match, $in match, comparison match
* One way to make it better would be to enable the use of multiple indexes if the first usable index
* returns too much data. I may do it in the future.
*
* TODO: needs to be moved to the Cursor module
*/
getCandidates(query: any): void;
/**
* Insert a new document
* @param cb Optional callback, signature: err, insertedDoc
*/
insert<T>(newDoc: T, cb?: (err: Error, document: T) => void): void;
/**
* Count all documents matching the query
* @param query MongoDB-style query
*/
count(query: any, callback: (err: Error, n: number) => void): void;
count(query: any): Nedb.CursorCount;
/**
* Find all documents matching the query
* If no callback is passed, we return the cursor so that user can limit, skip and finally exec
* @param query MongoDB-style query
* @param projection MongoDB-style projection
*/
find<T>(query: any, projection: T, callback: (err: Error, documents: T[]) => void): void;
find<T>(query: any, projection?: T): Nedb.Cursor<T>;
/**
* Find all documents matching the query
* If no callback is passed, we return the cursor so that user can limit, skip and finally exec
* * @param {any} query MongoDB-style query
*/
find<T>(query: any, callback: (err: Error, documents: T[]) => void): void;
/**
* Find one document matching the query
* @param query MongoDB-style query
* @param projection MongoDB-style projection
*/
findOne<T>(query: any, projection: T, callback: (err: Error, document: T) => void): void;
/**
* Find one document matching the query
* @param query MongoDB-style query
*/
findOne<T>(query: any, callback: (err: Error, document: T) => void): void;
/**
* Update all docs matching query v1.7.4 and prior signature.
* For now, very naive implementation (recalculating the whole database)
* @param options Optional options
* options.multi If true, can update multiple documents (defaults to false)
* options.upsert If true, document is inserted if the query doesn't match anything
* @param cb Optional callback, signature: err,
* numReplaced,
* upsert (set to true if the update was in fact an upsert)
*
* @api private Use Datastore.update which has the same signature
*/
update(query: any, updateQuery: any, options?: Nedb.UpdateOptions, cb?: (err: Error, numberOfUpdated: number, upsert: boolean) => void): void;
/**
* Update all docs matching query v1.8 signature.
* For now, very naive implementation (recalculating the whole database)
* @param options Optional options
* options.multi If true, can update multiple documents (defaults to false)
* options.upsert If true, document is inserted if the query doesn't match anything
* @param cb Optional callback, signature: err,
* numAffected,
* affectedDocuments (when returnUpdatedDocs is set to true), obj or array
* upsert (set to true if the update was in fact an upsert)
*
* @api private Use Datastore.update which has the same signature
*/
update<T>(query: any, updateQuery: any, options?: Nedb.UpdateOptions, cb?: (err: Error, numberOfUpdated: number, affectedDocuments: any, upsert: boolean) => void): void;
/**
* Remove all docs matching the query
* For now very naive implementation (similar to update)
* @param options Optional options
* options.multi If true, can update multiple documents (defaults to false)
* @param cb Optional callback, signature: err, numRemoved
*
* @api private Use Datastore.remove which has the same signature
*/
remove(query: any, options: Nedb.RemoveOptions, cb?: (err: Error, n: number) => void): void;
remove(query: any, cb?: (err: Error, n: number) => void): void;
}
declare namespace Nedb {
interface Cursor<T> {
sort(query: any): Cursor<T>;
skip(n: number): Cursor<T>;
limit(n: number): Cursor<T>;
projection(query: any): Cursor<T>;
exec(callback: (err: Error, documents: T[]) => void): void;
}
interface CursorCount {
exec(callback: (err: Error, count: number) => void): void;
}
interface DataStoreOptions {
filename?: string; // Optional, datastore will be in-memory only if not provided
inMemoryOnly?: boolean; // Optional, default to false
nodeWebkitAppName?: boolean; // Optional, specify the name of your NW app if you want options.filename to be relative to the directory where
autoload?: boolean; // Optional, defaults to false
// Optional, if autoload is used this will be called after the load database with the error object as parameter. If you don't pass it the error will be thrown
onload?(error: Error): any;
// (optional): hook you can use to transform data after it was serialized and before it is written to disk.
// Can be used for example to encrypt data before writing database to disk.
// This function takes a string as parameter (one line of an NeDB data file) and outputs the transformed string, which must absolutely not contain a \n character (or data will be lost)
afterSerialization?(line: string): string;
// (optional): reverse of afterSerialization.
// Make sure to include both and not just one or you risk data loss.
// For the same reason, make sure both functions are inverses of one another.
// Some failsafe mechanisms are in place to prevent data loss if you misuse the serialization hooks:
// NeDB checks that never one is declared without the other, and checks that they are reverse of one another by testing on random strings of various lengths.
// In addition, if too much data is detected as corrupt,
// NeDB will refuse to start as it could mean you're not using the deserialization hook corresponding to the serialization hook used before (see below)
beforeDeserialization?(line: string): string;
// (optional): between 0 and 1, defaults to 10%. NeDB will refuse to start if more than this percentage of the datafile is corrupt.
// 0 means you don't tolerate any corruption, 1 means you don't care
corruptAlertThreshold?: number;
// (optional, defaults to false)
// timestamp the insertion and last update of all documents, with the fields createdAt and updatedAt. User-specified values override automatic generation, usually useful for testing.
timestampData?: boolean;
}
/**
* multi (defaults to false) which allows the modification of several documents if set to true
* upsert (defaults to false) if you want to insert a new document corresponding to the update rules if your query doesn't match anything
*/
interface UpdateOptions {
multi?: boolean;
upsert?: boolean;
returnUpdatedDocs?: boolean;
}
/**
* options only one option for now: multi which allows the removal of multiple documents if set to true. Default is false
*/
interface RemoveOptions {
multi?: boolean;
}
interface EnsureIndexOptions {
fieldName: string;
unique?: boolean;
sparse?: boolean;
}
interface Persistence {
compactDatafile(): void;
setAutocompactionInterval(interval: number): void;
stopAutocompaction(): void;
}
}

20
src/plugins/nedb/index.ts Normal file
View File

@@ -0,0 +1,20 @@
// import Nedb from 'nedb-async'
// import { Datastore } from 'nedb-async-await'
// @ts-ignore
import Nedb from 'nedb'
const setting = new Nedb({
filename: 'setting',
autoload: true
})
const video = new Nedb({
filename: 'video',
autoload: true
})
export {
setting,
video
}

View File

@@ -0,0 +1,28 @@
import { setting } from './index'
export default {
add (data: any): Promise<any> {
return new Promise((resolve, reject) => {
setting.insert(data, (err: any, doc: any) => {
reject(err)
resolve(doc)
})
})
},
find (data?: any): Promise<any> {
return new Promise((resolve, reject) => {
setting.find(data, (err: any, doc: any) => {
reject(err)
resolve(doc)
})
})
},
update (id: string, data: any): Promise<any> {
return new Promise((resolve, reject) => {
setting.update({ _id: id }, { $set: data }, {}, (err: any, num: number) => {
reject(err)
resolve(num)
})
})
}
}

View File

@@ -12,7 +12,8 @@
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
"webpack-env",
"nedb"
],
"paths": {
"@/*": [

View File

@@ -927,6 +927,13 @@
resolved "https://registry.npm.taobao.org/@types/minimatch/download/@types/minimatch-3.0.3.tgz?cache=0&sync_timestamp=1572464707542&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40types%2Fminimatch%2Fdownload%2F%40types%2Fminimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d"
integrity sha1-PcoOPzOyAPx9ETnAzZbBJoyt/Z0=
"@types/nedb@^1.8.5", "@types/nedb@^1.8.9":
version "1.8.9"
resolved "http://r.cnpmjs.org/@types/nedb/download/@types/nedb-1.8.9.tgz#3cb80a94dfe41bea1dc33c4ea39cd4e7f754abc4"
integrity sha1-PLgKlN/kG+odwzxOo5zU5/dUq8Q=
dependencies:
"@types/node" "*"
"@types/node@*":
version "13.1.6"
resolved "https://registry.npm.taobao.org/@types/node/download/@types/node-13.1.6.tgz?cache=0&sync_timestamp=1578585994687&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40types%2Fnode%2Fdownload%2F%40types%2Fnode-13.1.6.tgz#076028d0b0400be8105b89a0a55550c86684ffec"
@@ -1751,6 +1758,11 @@ async-validator@~1.8.1:
dependencies:
babel-runtime "6.x"
async@0.2.10:
version "0.2.10"
resolved "http://r.cnpmjs.org/async/download/async-0.2.10.tgz#b6bbe0b0674b9d719708ca38de8c237cb526c3d1"
integrity sha1-trvgsGdLnXGXCMo43owjfLUmw9E=
async@^2.0.0, async@^2.6.2:
version "2.6.3"
resolved "https://registry.npm.taobao.org/async/download/async-2.6.3.tgz#d72625e2344a3656e3a3ad4fa749fa83299d82ff"
@@ -1902,6 +1914,13 @@ binary-extensions@^2.0.0:
resolved "https://registry.npm.taobao.org/binary-extensions/download/binary-extensions-2.0.0.tgz#23c0df14f6a88077f5f986c0d167ec03c3d5537c"
integrity sha1-I8DfFPaogHf1+YbA0WfsA8PVU3w=
binary-search-tree@0.2.5:
version "0.2.5"
resolved "http://r.cnpmjs.org/binary-search-tree/download/binary-search-tree-0.2.5.tgz#7dbb3b210fdca082450dad2334c304af39bdc784"
integrity sha1-fbs7IQ/coIJFDa0jNMMErzm9x4Q=
dependencies:
underscore "~1.4.4"
bindings@^1.5.0:
version "1.5.0"
resolved "https://registry.npm.taobao.org/bindings/download/bindings-1.5.0.tgz#10353c9e945334bc0511a6d90b38fbc7c9c504df"
@@ -5957,6 +5976,13 @@ levn@^0.3.0, levn@~0.3.0:
prelude-ls "~1.1.2"
type-check "~0.3.2"
lie@3.1.1:
version "3.1.1"
resolved "http://r.cnpmjs.org/lie/download/lie-3.1.1.tgz#9a436b2cc7746ca59de7a41fa469b3efb76bd87e"
integrity sha1-mkNrLMd0bKWd56QfpGmz77dr2H4=
dependencies:
immediate "~3.0.5"
lie@~3.3.0:
version "3.3.0"
resolved "https://registry.npm.taobao.org/lie/download/lie-3.3.0.tgz#dcf82dee545f46074daf200c7c1c5a08e0f40f6a"
@@ -6022,6 +6048,13 @@ loader-utils@^1.0.2, loader-utils@^1.1.0, loader-utils@^1.2.3:
emojis-list "^2.0.0"
json5 "^1.0.1"
localforage@^1.3.0:
version "1.7.3"
resolved "http://r.cnpmjs.org/localforage/download/localforage-1.7.3.tgz#0082b3ca9734679e1bd534995bdd3b24cf10f204"
integrity sha1-AIKzypc0Z54b1TSZW907JM8Q8gQ=
dependencies:
lie "3.1.1"
locate-path@^2.0.0:
version "2.0.0"
resolved "https://registry.npm.taobao.org/locate-path/download/locate-path-2.0.0.tgz#2b568b265eec944c6d9c0de9c3dbbbca0354cd8e"
@@ -6551,6 +6584,33 @@ natural-compare@^1.4.0:
resolved "https://registry.npm.taobao.org/natural-compare/download/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7"
integrity sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=
nedb-async-await@^0.1.2:
version "0.1.2"
resolved "http://r.cnpmjs.org/nedb-async-await/download/nedb-async-await-0.1.2.tgz#cd71a7ce4a4181cf186d974e547eac2a9eb2105a"
integrity sha1-zXGnzkpBgc8YbZdOVH6sKp6yEFo=
dependencies:
"@types/nedb" "^1.8.5"
nedb "^1.8.0"
thenify "^3.3.0"
nedb-async@^0.1.3:
version "0.1.3"
resolved "http://r.cnpmjs.org/nedb-async/download/nedb-async-0.1.3.tgz#56c3f3fc3c917bcda70f3c55c0f4fd81abece4be"
integrity sha1-VsPz/DyRe82nDzxVwPT9gavs5L4=
dependencies:
nedb "^1.8.0"
nedb@^1.8.0:
version "1.8.0"
resolved "http://r.cnpmjs.org/nedb/download/nedb-1.8.0.tgz#0e3502cd82c004d5355a43c9e55577bd7bd91d88"
integrity sha1-DjUCzYLABNU1WkPJ5VV3vXvZHYg=
dependencies:
async "0.2.10"
binary-search-tree "0.2.5"
localforage "^1.3.0"
mkdirp "~0.5.1"
underscore "~1.4.4"
negotiator@0.6.2:
version "0.6.2"
resolved "https://registry.npm.taobao.org/negotiator/download/negotiator-0.6.2.tgz#feacf7ccf525a77ae9634436a64883ffeca346fb"
@@ -9224,7 +9284,7 @@ thenify-all@^1.0.0:
dependencies:
thenify ">= 3.1.0 < 4"
"thenify@>= 3.1.0 < 4":
"thenify@>= 3.1.0 < 4", thenify@^3.3.0:
version "3.3.0"
resolved "https://registry.npm.taobao.org/thenify/download/thenify-3.3.0.tgz#e69e38a1babe969b0108207978b9f62b88604839"
integrity sha1-5p44obq+lpsBCCB5eLn2K4hgSDk=
@@ -9543,6 +9603,11 @@ uglify-js@^3.1.4:
commander "~2.20.3"
source-map "~0.6.1"
underscore@~1.4.4:
version "1.4.4"
resolved "http://r.cnpmjs.org/underscore/download/underscore-1.4.4.tgz#61a6a32010622afa07963bf325203cf12239d604"
integrity sha1-YaajIBBiKvoHljvzJSA88SI51gQ=
unicode-canonical-property-names-ecmascript@^1.0.4:
version "1.0.4"
resolved "https://registry.npm.taobao.org/unicode-canonical-property-names-ecmascript/download/unicode-canonical-property-names-ecmascript-1.0.4.tgz#2619800c4c825800efdd8343af7dd9933cbe2818"