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

How to use the typescript definition to write browser only code? #415

Open
selganor74 opened this issue May 9, 2016 · 1 comment
Open

Comments

@selganor74
Copy link

selganor74 commented May 9, 2016

I'm trying to use nedb with typescript but I didn't find a way to instantiate an NeDBDatastore using the d.ts that comes with

typings install dt!nedb -S --ambient

The application is actually structured using typescript namespaces only.

When I try to add

import * as Nedb from "nedb";

on top of my file, the namespaces defined in the same file becomes "invisible" by other scripts referencing it.

I'm still not very familiar with modules in typescript, so this may be asilly question, and I'm sorry if it really is! But any help would be really appreciated, thank you!

import * as Nedb from "nedb";

/**
 * Repository implementation for the NeDB database.
 */
namespace Repository.NeDBImplementation {

    [...]    

      export abstract class BaseNeDBRepository
        <
            T extends BaseAggregateRoot<T, TKey>,
            TKey extends IKeyValueObject<TKey>
        > implements IRepository<T, TKey> { 

            private datastore: Nedb;

            constructor(
                private options?: NeDB.DataStoreOptions
            ) {
                this.datastore = new Nedb(options); // This seems to be fine to the compiler
            }

            [...]        
      }
}

@selganor74
Copy link
Author

selganor74 commented May 17, 2016

I made further research and I learned about the evil difference between "internal" and "external" "modules". This link is the one that gave me more insight regarding this particular issue: microsoft/TypeScript#557. In this link Ryan Cavanaugh aswers telling that a typescript definitions file should be developed using an "internal/external" pattern, but I don't know what is it. In the end, my solution had been to edit the index.d.ts in Installed by typings with my version that follows... I really don't if this is the correct solution, if it is, feel free to integrate it in your code ;-) - Thank you !

// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/48352f5f291965cd71226283ff3ed79a7b119d2b/nedb/nedb.d.ts
// Type definitions for NeDB
// Project: https://github.com/louischatriot/nedb
// Definitions by: Stefan Steinhart <https://github.com/reppners>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

declare module "nedb" {

    class NeDBDataStore {
        [...]
    }

    namespace NeDBDataStore {}
    export = NeDBDataStore;
}

declare namespace NeDB {
    /////////////////////
     /// I have simply copied and pasted the class NeDBDatastore defined in the module upstairs !!!
    ///////////
    class NeDBDataStore {
        [...]
    }

    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:Array<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
        onload?:(error:Error)=>any // 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
        afterSerialization?:(line:string)=>string; // (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)
        beforeDeserialization?:(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)
        corruptAlertThreshold?:number; // (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
    }

    /**
     * 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;
    }
}

then within my internal modules I can refer to the NeDBDatastore in this way:

/// <reference path="../../typings/browser.d.ts" />


declare var Nedb: typeof NeDB.NeDBDataStore;


which leaves me in the world of the internal modules ... phew!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant