Skip to content

Commit e801ea5

Browse files
committed
deal with no connection
1 parent 6976c96 commit e801ea5

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

packages/mongodb-ts-autocomplete/src/autocompleter.spec.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,17 @@ describe('MongoDBAutocompleter', function () {
4949
});
5050
});
5151

52+
it('deals with no connection', async function () {
53+
autocompleterContext.currentDatabaseAndConnection = () => {
54+
const error = new Error('No connection');
55+
error.name = 'MongoshInvalidInputError';
56+
throw error;
57+
};
58+
59+
const completions = await autocompleter.autocomplete('db.');
60+
expect(completions).to.deep.equal([]);
61+
});
62+
5263
it('does not leak the bson package', async function () {
5364
const completions = await autocompleter.autocomplete('bson.');
5465
expect(completions).to.deep.equal([]);

packages/mongodb-ts-autocomplete/src/autocompleter.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,8 +202,21 @@ declare global {
202202
}
203203

204204
async autocomplete(code: string): Promise<AutoCompletion[]> {
205-
const { connectionId, databaseName } =
206-
this.context.currentDatabaseAndConnection();
205+
let connectionId: string;
206+
let databaseName: string;
207+
208+
// If there's no known connection, currentDatabaseAndConnection() will
209+
// error, but we won't be able to generate types for a connection, db
210+
// object, etc, anyway. So just return no results in that case.
211+
try {
212+
({ connectionId, databaseName } =
213+
this.context.currentDatabaseAndConnection());
214+
} catch (err: any) {
215+
if (err.name === 'MongoshInvalidInputError') {
216+
return [];
217+
}
218+
throw err;
219+
}
207220

208221
const tsAst = compileSourceFile(code);
209222
const collectionName = inferCollectionNameFromFunctionCall(tsAst) || 'test';

0 commit comments

Comments
 (0)