TypeScript support?

I can’t figure out how to use the SDK 3.1 with my TypeScript project.

The only module declared (in .d.ts) is “couchbase” , containing no members (except connect function) and none of the types are exported.

attempting to import or use anything from couchbase fails:

import {Cluster} from “couchbase” - fails, Cluster is declared but not exported
import {Bucket} from “couchbase” - fails, Bucket is declared, but not exported, etc

On top of this, the type definitions appear to be out of date (UPDATE: see below, the types are not out of date, the documentation is)

As such, I’m totally lost as to how to use this SDK with TypeScript.

I’m also exp. the same issue. As a temporary workaround I have a build script that exports all the declared members from the types.d.ts file. To get familiar with the SDK/API changes you could search/replace declare with export declare. Note that when they fix the types.d.ts file during their build process it could break your imports. Hope this helps

-Mark

This is precisely what I don’t want to do. I have to imagine we’re using the SDK in some unintended manner. Can it really be true that the entire Node SDK exposes only a single exported property (lcbVersion) and a single exported method (connect) across the entire module?

In addition, the documentation for the 3.1 SDK appears to be outdated/incorrect:

//WRONG - unsupported by SDK 3.1
const cb = require('couchbase')
const cluster = new cb.Cluster('couchbase://localhost', {
     username: 'user',
     password: 'pass'
 })
//CORRECT
import * as couchbase from "couchbase"
const cluster = await couchbase.connect('couchbase://localhost', {
       username:'user',
       password: 'pass'
 })

Help!

I found ONE way to import that seems to be holding for now.

Critically, it uses a completely different connection method than is detailed in the Node SDK 3.1 documentation AND it imports couchbase as a whole.

app.ts:

//couchbase types
import * as couchbase from "couchbase"

export class App {
    cluster: Cluster | null = null
    async connectToDb() {
        //connect using the SDK's API, rather than instruction in docs
        // i.e. new couchbase.Cluster() is unsupported in SDK 3.1
        const cluster = await couchbase.connect('couchbase://localhost', {
            username: 'user',
            password: 'pass'
        }
         //type works correctly - you MUST await or then(), because the Cluster
         // instance is only available via the returned Promise
        this.cluster = cluster
    }
}

If this is the correct usage in 3.1, please update docs at once.l

For me your approach works to get the compiler working. However, when I use it, I get run-time exceptions:

ReferenceError: SearchQuery is not defined

The cluster works / connects, but it seems everything else in the SDK is unavailable since the members aren’t exported in the definition file.

For SDK v 3.1.0, doing:

import * as couchbase from "couchbase"

gives me access to the non-exported types (I only need Cluster and Bucket for now, but other types including SearchQuery are accessible via the import without Error)

Here’s a working query example (after setting this.cluster (above)):

async performQuery() {
    const res = await this.cluster!.query("SELECT bucket.* FROM bucket WHERE meta().id = 'mydocument'")
    //Loop thru rows, each is an object
    res.rows.forEach((row: Object) => {
         //cast the the row to my expected type
         const myobject = <MyClass>row
         console.log(`doing something with cluster: ${myobject.prop1}`)
    })
}

My tsconfig.json file looks like:

{
  "compilerOptions": {
    /* Basic Options */
    "target": "ES6",
    "module": "commonjs",
    /* skip corresponding '.d.ts' file. */
    "declaration": false,
    /* Redirect output structure to the directory. */
    "outDir": "dist",
    /* Enable all strict type-checking options. */
    "strict": true,
    /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "allowSyntheticDefaultImports": true,
    /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "esModuleInterop": true,
    //allow Javascript imports in TypeScript
    "allowJs": true
  }
}

Hope this helps

@Robert_Mirabelle thanks for the help. I was able to get a basic query working with your sample, but still hit a reference error when executing a full text search using the API. Going wait on this a bit with the hope the SDK dev(s) will review this thread and update the def file and / or create some working TypeScript samples.

result = await cluster.searchQuery(this.config.bucket, SearchQuery.queryString(query), { skip: start, limit: limit });

Output from above:
testing RobertsTest…
*** cluster created ***
query +docType:RequestHeader
ReferenceError: SearchQuery is not defined

We have a similar issue when we converted our error handling code to Typescript.
The code below will break with a ReferenceError at runtime

if (error instanceof couchbase.DocumentNotFoundError) {
return res.status(404).send({
error: error.message,
});
} if (error instanceof couchbase.DocumentExistsError) {
return res.status(409).send({
error: error.message,
});
} if (error instanceof couchbase.CouchbaseError) {
return res.status(505).send({
error: couchbase error: ${error.message},
});
}

I believe the culprit is that the CouchbaseError classes have not been exported properly in the *.d.ts file.

Hey Everyone,

We have actually rewritten the Node.js SDK properly into TypeScript rather than using externally described type annotations. This should drive a substantially better experience when using TypeScript. It is currently published as alpha and should move towards beta in the near future. We’ve published outside the scope of a 3.2 GA release as the conversion may have introduced some compatibility issues with the 3.1 SDK and are looking to get some feedback on that before we transition fully, though it generally is a 1:1 conversion. Let us know if you run into any issues and we would be happy to get those resolved ASAP!

Cheers, Brett

1 Like

The build couchbase@3.2.0-alpha.1 is incomplete.
dist folder was missing
Error: Cannot find module ‘C:\Users\vicky\Projects\NPM\couchbase-session\node_modules\couchbase\dist\couchbase.js’. Please verify that the package.json has a valid “main” entry

Hey @Vigneshwaran_Rengana,

3.2.0-alpha.2 has been published which should correctly include the needed /dist/ folder. It looks like there was an issue with generating the dist folder which didn’t appear during the dry-run test.

Cheers, Brett

Thanks for your quick response, How can I fix that?

Hey @Vigneshwaran_Rengana ,

It was an issue on our side. If you install couchnode using npm install couchbase@3.2.0-alpha.2, it should grab the fixed version I published this morning.

Cheers, Brett

Getting following error on building the solution with couchbase@3.2.0-alpha.2 -

/node_modules/couchbase/dist/streamablepromises.d.ts(2,8): error TS1259: Module ‘“events”’ can only be default-imported using the ‘esModuleInterop’ flag

Hey @Vratika_Jain ,

Have you tried enabling esModuleInterop flag in your tsconfig file?

Cheers, Brett

1 Like

Thanks for the quick response. This solved my issue.

Hi @brett19 ,
We are using couchbase 3.2.0-alpha.2
But when we try to connect to cluster, we are getting timeout error.
Our couchbase server is 6.5.1. Please help.

Regards,
Vratika

Hey @Vratika_Jain ,

You can start your application with debugging enabled to see more diagnostics details on why connecting failed (and lead to the operation timing out). You can do this by invoking your application like so: DEBUG=* node index.

Cheers, Brett

Hi,
We are using couchbase 3.2.0-alpha.2
Please refer the screenshot of error.
The way i connect to cluster is -
const options = { username:userName,
password,
kvTimeout: 3600000,
kvDurableTimeout: 3600000,
viewTimeout: 3600000,
queryTimeout: 3600000,
analyticsTimeout: 3600000,
searchTimeout: 3600000,
managementTimeout: 3600000};
const cluster = await couchbase.connect(endPointName, options);
const bucketValue = cluster.bucket(bucketName);
const collection = bucketValue.defaultCollection();

I receive intermittent timeout error . When i run query on cluster, it works most of the times. But when i run get() document by key on collection, i always receive timeout error or connection is closed error.

Hi @brett19 ,
Here is the diagnostic details -
couchbase connect issue.zip (6.9 KB)

Regards,
Vratika