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

feat!: throw error with out of bounds integer values instead of truncating, add custom 'integerValue' type cast option #488

Closed
wants to merge 22 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
60c0900
feat: handle outside of bounds numeric values, add custom 'integerVal…
AVaksman Sep 5, 2019
6d1c7cc
chore: add unit tests
AVaksman Sep 5, 2019
edeec3e
Merge branch 'master' into numeric_typeCast
AVaksman Sep 5, 2019
e882977
feat: add validation agains MIN_SAFE_INTEGER
AVaksman Sep 5, 2019
5863365
refactor: remove extra condition
AVaksman Sep 6, 2019
9358b68
Merge branch 'master' into numeric_typeCast
AVaksman Sep 6, 2019
a7856d8
Merge branch 'master' into numeric_typeCast
AVaksman Sep 6, 2019
5f5be01
Merge branch 'master' into numeric_typeCast
AVaksman Sep 9, 2019
8668bd5
refactor: more specific name
AVaksman Sep 9, 2019
e5b8635
Merge branch 'master' into numeric_typeCast
AVaksman Sep 11, 2019
d66115b
Merge branch 'master' into numeric_typeCast
JustinBeckwith Sep 11, 2019
40f2f90
Merge branch 'master' into numeric_typeCast
AVaksman Sep 12, 2019
4e6f530
refactor: use Number.isSafeInteger
AVaksman Sep 15, 2019
b856dc8
fix: docs
AVaksman Sep 16, 2019
e201f6e
fix: docs2
AVaksman Sep 17, 2019
4c2ba71
Merge branch 'master' into numeric_typeCast
AVaksman Sep 19, 2019
1366a7a
Merge branch 'master' into numeric_typeCast
AVaksman Sep 26, 2019
4fb2306
Merge branch 'master' into numeric_typeCast
AVaksman Oct 2, 2019
6770518
Merge branch 'master' into numeric_typeCast
AVaksman Oct 2, 2019
68ce578
Merge branch 'master' into numeric_typeCast
jkwlui Oct 3, 2019
7aa3617
Merge branch 'master' into numeric_typeCast
AVaksman Oct 7, 2019
4b7cb3e
Merge branch 'master' into numeric_typeCast
JustinBeckwith Oct 12, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 88 additions & 8 deletions src/entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import arrify = require('arrify');
import * as extend from 'extend';
import * as is from 'is';
import {Query, QueryProto} from './query';
import {Query, QueryProto, TypeCastConfig} from './query';
import {PathType} from '.';
import * as Protobuf from 'protobufjs';
import * as path from 'path';
Expand Down Expand Up @@ -326,11 +326,67 @@ export namespace entity {
return value instanceof entity.Key;
}

/**
* Convert a protobuf `integerValue`.
*
* @private
* @param {object} valueProto The protobuf `integerValue` to convert.
* @param {object} typeCastConfig Config for custom `integerValue` cast.
* @property {function} {typeCastConfig.typeCastFunction} A custom user
* provided function to convert `integerValue`.
* @property {sting|string[]} {typeCastConig.names} `Entity` property
jkwlui marked this conversation as resolved.
Show resolved Hide resolved
* names to be converted using `typeCastFunction`.
*/
function decodeIntegerValue(
valueProto: ValueProto,
typeCastConfig?: TypeCastConfig
) {
let customCast = false;
if (typeCastConfig) {
if (
!typeCastConfig.typeCastFunction ||
callmehiphop marked this conversation as resolved.
Show resolved Hide resolved
typeof typeCastConfig.typeCastFunction !== 'function'
) {
throw new Error(
`typeCastFunction is not a function or was not provided.`
);
}
customCast = true;
if (typeCastConfig.names) {
typeCastConfig.names = arrify(typeCastConfig.names);
if (!typeCastConfig.names.includes(valueProto.name!)) {
customCast = false;
}
}
}

if (customCast) {
try {
return typeCastConfig!.typeCastFunction(valueProto.integerValue);
} catch (error) {
throw new Error(`typeCastFunction threw an error:\n${error}`);
}
} else {
const num = Number(valueProto[`integerValue`]);
if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) {
throw new Error(
`Integer value ${valueProto[`integerValue`]} is out of bounds.`
);
}
return num;
}
}

/**
* Convert a protobuf Value message to its native value.
*
* @private
* @param {object} valueProto The protobuf Value message to convert.
* @param {object} typeCastConfig Config for custom `integerValue` cast.
* @property {function} {typeCastConfig.typeCastFunction} A custom user
* provided function to convert `integerValue`.
* @property {sting|string[]} [typeCastConfig.names] `Entity` property
* names to be converted using `typeCastFunction`.
* @returns {*}
*
* @example
Expand All @@ -349,13 +405,19 @@ export namespace entity {
* });
* // <Buffer 68 65 6c 6c 6f>
*/
export function decodeValueProto(valueProto: ValueProto) {
export function decodeValueProto(
valueProto: ValueProto,
typeCastConfig?: TypeCastConfig
) {
const valueType = valueProto.valueType!;
const value = valueProto[valueType];

switch (valueType) {
case 'arrayValue': {
return value.values.map(entity.decodeValueProto);
// tslint:disable-next-line no-any
return value.values.map((val: any) =>
entity.decodeValueProto(val, typeCastConfig)
);
}

case 'blobValue': {
Expand All @@ -371,7 +433,7 @@ export namespace entity {
}

case 'integerValue': {
return Number(value);
return decodeIntegerValue(valueProto, typeCastConfig);
}

case 'entityValue': {
Expand Down Expand Up @@ -504,6 +566,11 @@ export namespace entity {
*
* @private
* @param {object} entityProto The protocol entity object to convert.
* @param {object} typeCastConfig Config for custom `integerValue` cast.
* @property {function} {typeCastConfig.typeCastFunction} A custom user
* provided function to convert `integerValue`.
* @property {sting|string[]} [typeCastConfig.names] `Entity` property
* names to be converted using `typeCastFunction`.
* @returns {object}
*
* @example
Expand All @@ -524,15 +591,19 @@ export namespace entity {
* // }
*/
// tslint:disable-next-line no-any
export function entityFromEntityProto(entityProto: EntityProto): any {
export function entityFromEntityProto(
entityProto: EntityProto,
typeCastConfig?: TypeCastConfig
) {
// tslint:disable-next-line no-any
const entityObject: any = {};
const properties = entityProto.properties || {};

// tslint:disable-next-line forin
for (const property in properties) {
const value = properties[property];
entityObject[property] = entity.decodeValueProto(value);
value.name = property;
entityObject[property] = entity.decodeValueProto(value, typeCastConfig);
}

return entityObject;
Expand Down Expand Up @@ -718,6 +789,11 @@ export namespace entity {
* @param {object[]} results The response array.
* @param {object} results.entity An entity object.
* @param {object} results.entity.key The entity's key.
* @param {object} typeCastConfig Config for custom `integerValue` cast.
* @property {function} {typeCastConfig.typeCastFunction} A custom user
* provided function to convert `integerValue`.
* @property {sting|string[]} [typeCastConfig.names] `Entity` property
* names to be converted using `typeCastFunction`.
* @returns {object[]}
*
* @example
Expand All @@ -732,9 +808,12 @@ export namespace entity {
* //
* });
*/
export function formatArray(results: ResponseResult[]) {
export function formatArray(
results: ResponseResult[],
typeCastConfig?: TypeCastConfig
) {
return results.map(result => {
const ent = entity.entityFromEntityProto(result.entity!);
const ent = entity.entityFromEntityProto(result.entity!, typeCastConfig);
ent[entity.KEY_SYMBOL] = entity.keyFromKeyProto(result.entity!.key!);
return ent;
});
Expand Down Expand Up @@ -1175,6 +1254,7 @@ export interface ValueProto {
values?: ValueProto[];
// tslint:disable-next-line no-any
value?: any;
name?: string;
}

export interface EntityProto {
Expand Down
6 changes: 6 additions & 0 deletions src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -517,9 +517,15 @@ export interface QueryProto {
*/
export {Query};

export interface TypeCastConfig {
typeCastFunction: Function;
names?: string | string[];
}

export interface RunQueryOptions {
consistency?: 'strong' | 'eventual';
gaxOptions?: CallOptions;
typeCastConfig?: TypeCastConfig;
}

export interface RunQueryCallback {
Expand Down
25 changes: 19 additions & 6 deletions src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,10 @@ class DatastoreRequest {
return;
}

const entities = entity.formatArray(resp!.found! as ResponseResult[]);
const entities = entity.formatArray(
resp!.found! as ResponseResult[],
options.typeCastConfig
);
const nextKeys = (resp!.deferred || [])
.map(entity.keyFromKeyProto)
.map(entity.keyToKeyProto);
Expand Down Expand Up @@ -430,6 +433,11 @@ class DatastoreRequest {
* [here](https://cloud.google.com/datastore/docs/articles/balancing-strong-and-eventual-consistency-with-google-cloud-datastore).
* @param {object} [options.gaxOptions] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
* @param {object} [options.typeCastConfig] Config for custom `integerValue` cast.
* @property {function} {typeCastConfig.typeCastFunction} A custom user
* provided function to convert `integerValue`.
* @property {sting|string[]} [typeCastConfig.names] `Entity` property
* names to be converted using `typeCastFunction`.
* @param {function} callback The callback function.
* @param {?error} callback.err An error returned while making this request
* @param {object|object[]} callback.entity The entity object(s) which match
Expand Down Expand Up @@ -684,6 +692,11 @@ class DatastoreRequest {
* @param {object} [options] Optional configuration.
* @param {object} [options.gaxOptions] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
* @param {object} [options.typeCastConfig] Config for custom `integerValue` cast.
* @property {function} {typeCastConfig.typeCastFunction} A custom user
* provided function to convert `integerValue`.
* @property {sting|string[]} [typeCastConfig.names] `Entity` property
* names to be converted using `typeCastFunction`.
*
* @example
* datastore.runQueryStream(query)
Expand Down Expand Up @@ -755,7 +768,10 @@ class DatastoreRequest {
let entities: Entity[] = [];

if (resp.batch.entityResults) {
entities = entity.formatArray(resp.batch.entityResults);
entities = entity.formatArray(
resp.batch.entityResults,
options.typeCastConfig
);
}

// Emit each result right away, then get the rest if necessary.
Expand Down Expand Up @@ -1299,10 +1315,7 @@ export interface AllocateIdsOptions {
allocations?: number;
gaxOptions?: CallOptions;
}
export interface CreateReadStreamOptions {
consistency?: string;
gaxOptions?: CallOptions;
}
export interface CreateReadStreamOptions extends RunQueryOptions {}
export interface GetCallback {
(err?: Error | null, entity?: Entities): void;
}
Expand Down
Loading