const EventEmitter = require('events')
const datastore = require('nedb-promise')

class Store extends EventEmitter {
    constructor (filename = './store.db') {
        super()
        this.db = datastore({ filename, autoload: true })
        this.inited = this.init()
    }

    async init () {
        await this.db.ensureIndex({ fieldName: 'screenName', unique: true })
        const docs = await this.db.find({}, {screenName: 1})
        docs.forEach(({screenName}) => {
            this.emit('follow', screenName)
        })
    }

    async follow (screenName, chatId) {
        await this.inited
        
        const query = { screenName }
        const doc = { screenName, $addToSet: { chatIds: chatId } }
        
        const {chatIds} = await this.db.update(query, doc, { upsert: true, returnUpdatedDocs: true })
        
        if (chatIds.length === 1) {
            this.emit('follow', screenName)
        }
    }

    async unfollow (screenName, chatId) {
        await this.inited
        
        const query = { screenName }
        const doc = { screenName, $pull: { chatIds: chatId } }
        const {chatIds} = await this.db.update(query, doc, { returnUpdatedDocs: true })
        
        if (chatIds.length === 0) {
            this.emit('unfollow', screenName)
        }
    }

    async leave (chatId) {
        await this.inited

        const docs = await this.find({ $elemMatch: { chatIds: chatId } }, { screenName: 1 })
        await Promise.all(docs.map(async ({screenName}) => this.unfollow(screenName, chatId)))
    }

    async following (screenName) {
        await this.inited

        const docs = await this.find({ screenName }, { chatIds: 1 })

        return docs.length === 0 ? [] : docs[0].chatIds
    }
}

module.exports = Store
@@ -663,28 +663,16 @@
  doc = %7B
- screenName,
  $addToS
@@ -711,32 +711,46 @@
   %0A        const
+ %5BnumAffected,
  %7BchatIds%7D = awa
@@ -735,32 +735,33 @@
 ected, %7BchatIds%7D
+%5D
  = await this.db
@@ -819,33 +819,24 @@
 cs: true %7D)%0A
-        %0A
         if (
@@ -1059,20 +1059,8 @@
  = %7B
- screenName,
  $pu
@@ -1098,16 +1098,30 @@
    const
+ %5BnumAffected,
  %7BchatId
@@ -1122,16 +1122,17 @@
 chatIds%7D
+%5D
  = await
@@ -1378,24 +1378,27 @@
  await this.
+db.
 find(%7B $elem
@@ -1642,16 +1642,19 @@
 it this.
+db.
 find(%7B s

fix store