[Vuejs]-How do I persist and retrieve typescript objects using pouchdb?

0👍

This appears to work…

import PouchDB from 'pouchdb';

// Base class for all objects which are persisted in database
export class Document {

    readonly type: string;
    readonly _id: string;
    private _rev?: string; //set by database when document is inserted

    constructor(type: string, id_suffix?: string) {
        this.type = type;
        let unique_id: string = uuid();

        if (id_suffix === undefined) {
            this._id = '${type}_${unique_id}'
        }
        else {
            this._id = '${type}_${id_suffix}_${unique_id}'
        }
    }
}

db.put(t);

let output = db.get<Document>(t._id).then(function (doc){
    let x: Document = doc;
    return x;
})

0👍

For the records, as you cast the return value (eg. as Document) from a plain object (Pouchdb store JSON objects), you lost the prototype. So you have to rebuild an instance from scratch.

For example :

let output = db.get<Document>(t._id).then(function (doc){
    return new Document(
        doc.type,
        doc. id_suffix
    );
})

Or as suggested here, using Object.assign (haven’t test this way).

Leave a comment