Skip to content

Commit

Permalink
feat: allow schema to be specified at runtime (#406)
Browse files Browse the repository at this point in the history
* feat: allow schema to be specified at runtime
* fix(lint): Fix linting errors
* fix(lint): More linting errors
  • Loading branch information
revbingo authored and bencevans committed Jun 20, 2019
1 parent 6060bc2 commit 2de6675
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 15 deletions.
48 changes: 33 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -436,22 +436,17 @@ export class InfluxDB {
this._pool.addHost(`${host.protocol}://${host.host}:${host.port}`, host.options);
});

this._options.schema.forEach(schema => {
schema.database = schema.database || this._options.database;
const db = schema.database;
if (!db) {
throw new Error(
`Schema ${schema.measurement} doesn't have a database specified,` +
'and no default database is provided!',
);
}

if (!this._schema[db]) {
this._schema[db] = Object.create(null);
}
this._options.schema.forEach(schema => this._createSchema(schema));
}

this._schema[db][schema.measurement] = new Schema(schema);
});
/**
* Adds specified schema for better fields coercing.
*
* @param {ISchemaOptions} schema
* @memberof InfluxDB
*/
public addSchema(schema: ISchemaOptions): void {
this._createSchema(schema);
}

/**
Expand Down Expand Up @@ -1314,4 +1309,27 @@ export class InfluxDB {
}
};
}

/**
* Creates specified measurement schema
*
* @private
* @param {ISchemaOptions} schema
* @memberof InfluxDB
*/
private _createSchema(schema: ISchemaOptions): void {
schema.database = schema.database || this._options.database;
if (!schema.database) {
throw new Error(
`Schema ${schema.measurement} doesn't have a database specified,` +
'and no default database is provided!',
);
}

if (!this._schema[schema.database]) {
this._schema[schema.database] = Object.create(null);
}

this._schema[schema.database][schema.measurement] = new Schema(schema);
}
}
31 changes: 31 additions & 0 deletions test/unit/influx.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,37 @@ describe('influxdb', () => {
]);
});

it('can accept a schema at runtime', () => {
setDefaultDB('my_db');
expectWrite('my_runtime_schema_measure,my_tag=1 bool=T,float=43,int=42i', {
precision: 'n',
rp: undefined,
db: 'my_db'
});

influx.addSchema({
database: 'my_db',
measurement: 'my_runtime_schema_measure',
fields: {
bool: FieldType.BOOLEAN,
float: FieldType.FLOAT,
int: FieldType.INTEGER
},
tags: ['my_tag']
});
return influx.writePoints([
{
measurement: 'my_runtime_schema_measure',
tags: {my_tag: '1'},
fields: {
int: 42,
float: 43,
bool: true
}
}
]);
});

it('throws on schema violations', () => {
setDefaultDB('my_db');

Expand Down

0 comments on commit 2de6675

Please sign in to comment.