1 | const QUERY_OPERATORS = require('./constants/query-operators');
|
2 | const BSON_TYPES = require('./constants/bson-types');
|
3 | const JSON_SCHEMA = require('./constants/json-schema');
|
4 | const BSON_TYPE_ALIASES = require('./constants/bson-type-aliases');
|
5 | const filter = require('./filter');
|
6 |
|
7 | /**
|
8 | * String token type.
|
9 | */
|
10 | const STRING = 'string';
|
11 |
|
12 | /**
|
13 | * The match completions.
|
14 | */
|
15 | const MATCH_COMPLETIONS = QUERY_OPERATORS.concat(BSON_TYPES);
|
16 |
|
17 | /**
|
18 | * Adds autocomplete suggestions for validation queries.
|
19 | */
|
20 | class ValidationAutoCompleter {
|
21 | /**
|
22 | * Instantiate a new completer.
|
23 | *
|
24 | * @param {String} version - The version.
|
25 | * @param {TextCompleter} textCompleter - The fallback Ace text completer.
|
26 | * @param {Array} fields - The collection fields.
|
27 | */
|
28 | constructor(version, textCompleter, fields) {
|
29 | this.version = version;
|
30 | this.textCompleter = textCompleter;
|
31 | this.fields = fields;
|
32 | }
|
33 |
|
34 | /**
|
35 | * Update the autocompleter with new fields.
|
36 | *
|
37 | * @param {Array} fields - The new fields.
|
38 | */
|
39 | update(fields) {
|
40 | this.fields = fields;
|
41 | }
|
42 |
|
43 | /**
|
44 | * Get the completion list for the provided params.
|
45 | *
|
46 | * @param {Editor} editor - The ACE editor.
|
47 | * @param {EditSession} session - The current editor session.
|
48 | * @param {Position} position - The cursor position.
|
49 | * @param {String} prefix - The string prefix to complete.
|
50 | * @param {Function} done - The done callback.
|
51 | *
|
52 | * @returns {Function} The completion function.
|
53 | */
|
54 | getCompletions(editor, session, position, prefix, done) {
|
55 | // Empty prefixes do not return results.
|
56 | if (prefix === '') return done(null, []);
|
57 | // If the current token is a string with single or double quotes, then
|
58 | // we want to suggest document fields instead of suggesting operators.
|
59 | const currentToken = session.getTokenAt(position.row, position.column);
|
60 | if (currentToken.type === STRING) {
|
61 | const strings = BSON_TYPE_ALIASES.concat(this.fields);
|
62 | return done(null, filter(this.version, strings, prefix));
|
63 | }
|
64 | // If the current token is not a string, then we proceed as normal to suggest
|
65 | // operators to the user.
|
66 | const expressions = MATCH_COMPLETIONS.concat(this.fields, JSON_SCHEMA);
|
67 | return done(null, filter(this.version, expressions, prefix));
|
68 | }
|
69 | }
|
70 |
|
71 | module.exports = ValidationAutoCompleter;
|