Socket
Socket
Sign inDemoInstall

database-ql

Package Overview
Dependencies
7
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.0.0-beta.12 to 1.0.0-beta.14

.eslintrc

13

dist/commonjs/aggregate.js

@@ -36,3 +36,3 @@ "use strict";

collectionName: this._collectionName,
stages: this._stages
stages: this._stages,
});

@@ -45,3 +45,3 @@ if (res.error) {

ok: false,
code: res.code
code: res.code,
};

@@ -53,3 +53,3 @@ }

requestId: res.requestId,
ok: true
ok: true,
};

@@ -64,3 +64,3 @@ return result;

return {
[stageKey]: JSON.parse(stageValue)
[stageKey]: JSON.parse(stageValue),
};

@@ -80,3 +80,3 @@ });

stageKey: raw ? stage : `$${stage}`,
stageValue: transformParam
stageValue: transformParam,
});

@@ -102,3 +102,4 @@ return this;

// 判断是否有 distanceMultiplier 参数
if (param.distanceMultiplier && typeof (param.distanceMultiplier) === 'number') {
if (param.distanceMultiplier &&
typeof param.distanceMultiplier === 'number') {
param.distanceMultiplier = param.distanceMultiplier * EARTH_RADIUS;

@@ -105,0 +106,0 @@ }

@@ -25,3 +25,3 @@ import { DocumentReference } from './document';

*/
add(data: Object, options?: {
add(data: object, options?: {
multi: boolean;

@@ -28,0 +28,0 @@ }): Promise<import("./result-types").AddRes>;

@@ -45,3 +45,3 @@ "use strict";

add(data, options) {
let docRef = new document_1.DocumentReference(this._db, this._coll, undefined);
const docRef = new document_1.DocumentReference(this._db, this._coll, undefined);
return docRef.create(data, options);

@@ -56,3 +56,3 @@ }

async createIndex(keys, options) {
let docRef = new document_1.DocumentReference(this._db, this._coll, undefined);
const docRef = new document_1.DocumentReference(this._db, this._coll, undefined);
return docRef.createIndex(keys, options);

@@ -64,7 +64,7 @@ }

async dropIndex(index) {
let docRef = new document_1.DocumentReference(this._db, this._coll, undefined);
const docRef = new document_1.DocumentReference(this._db, this._coll, undefined);
return docRef.dropIndex(index);
}
async listIndexes() {
let docRef = new document_1.DocumentReference(this._db, this._coll, undefined);
const docRef = new document_1.DocumentReference(this._db, this._coll, undefined);
return docRef.listIndexes();

@@ -71,0 +71,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable prefer-rest-params */
const query_1 = require("./commands/query");

@@ -61,15 +62,23 @@ const logic_1 = require("./commands/logic");

and(...__expressions__) {
const expressions = type_1.isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
const expressions = type_1.isArray(arguments[0])
? arguments[0]
: Array.from(arguments);
return new logic_1.LogicCommand(logic_1.LOGIC_COMMANDS_LITERAL.AND, expressions);
},
nor(...__expressions__) {
const expressions = type_1.isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
const expressions = type_1.isArray(arguments[0])
? arguments[0]
: Array.from(arguments);
return new logic_1.LogicCommand(logic_1.LOGIC_COMMANDS_LITERAL.NOR, expressions);
},
or(...__expressions__) {
const expressions = type_1.isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
const expressions = type_1.isArray(arguments[0])
? arguments[0]
: Array.from(arguments);
return new logic_1.LogicCommand(logic_1.LOGIC_COMMANDS_LITERAL.OR, expressions);
},
not(...__expressions__) {
const expressions = type_1.isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
const expressions = type_1.isArray(arguments[0])
? arguments[0]
: Array.from(arguments);
return new logic_1.LogicCommand(logic_1.LOGIC_COMMANDS_LITERAL.NOT, expressions);

@@ -97,3 +106,3 @@ },

$sort: options.sort,
$slice: options.slice
$slice: options.slice,
};

@@ -142,3 +151,3 @@ }

return {
$expr: values
$expr: values,
};

@@ -148,3 +157,3 @@ },

return {
$jsonSchema: schema
$jsonSchema: schema,
};

@@ -155,3 +164,3 @@ },

return {
$search: values.search
$search: values.search,
};

@@ -164,3 +173,3 @@ }

$caseSensitive: values.caseSensitive,
$diacriticSensitive: values.diacriticSensitive
$diacriticSensitive: values.diacriticSensitive,
};

@@ -283,8 +292,8 @@ }

// 变量声明操作符
let: (param) => new AggregationOperator('let', param)
let: (param) => new AggregationOperator('let', param),
},
project: {
slice: (param) => new ProjectionOperator('slice', param),
elemMatch: (param) => new ProjectionOperator('elemMatch', param)
}
elemMatch: (param) => new ProjectionOperator('elemMatch', param),
},
};

@@ -291,0 +300,0 @@ class AggregationOperator {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable prefer-rest-params */
const symbol_1 = require("../helper/symbol");

@@ -74,3 +75,3 @@ const query_1 = require("./query");

_setFieldName(fieldName) {
const operands = this.operands.map(operand => {
const operands = this.operands.map((operand) => {
if (operand instanceof LogicCommand) {

@@ -91,3 +92,5 @@ return operand._setFieldName(fieldName);

and(...__expressions__) {
const expressions = Array.isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
const expressions = Array.isArray(arguments[0])
? arguments[0]
: Array.from(arguments);
expressions.unshift(this);

@@ -101,3 +104,5 @@ return new LogicCommand(LOGIC_COMMANDS_LITERAL.AND, expressions, this.fieldName);

or(...__expressions__) {
const expressions = Array.isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
const expressions = Array.isArray(arguments[0])
? arguments[0]
: Array.from(arguments);
expressions.unshift(this);

@@ -109,9 +114,11 @@ return new LogicCommand(LOGIC_COMMANDS_LITERAL.OR, expressions, this.fieldName);

function isLogicCommand(object) {
return object && (object instanceof LogicCommand) && (object._internalType === symbol_1.SYMBOL_LOGIC_COMMAND);
return (object &&
object instanceof LogicCommand &&
object._internalType === symbol_1.SYMBOL_LOGIC_COMMAND);
}
exports.isLogicCommand = isLogicCommand;
function isKnownLogicCommand(object) {
return isLogicCommand && (object.operator.toUpperCase() in LOGIC_COMMANDS_LITERAL);
return (isLogicCommand && object.operator.toUpperCase() in LOGIC_COMMANDS_LITERAL);
}
exports.isKnownLogicCommand = isKnownLogicCommand;
exports.default = LogicCommand;

@@ -52,7 +52,7 @@ "use strict";

return {
['$' + this.operator]: this.operands
['$' + this.operator]: this.operands,
};
default:
return {
['$' + this.operator]: this.operands[0]
['$' + this.operator]: this.operands[0],
};

@@ -111,3 +111,4 @@ }

geoWithin(val) {
if (!(val.geometry instanceof index_1.MultiPolygon) && !(val.geometry instanceof index_1.Polygon)) {
if (!(val.geometry instanceof index_1.MultiPolygon) &&
!(val.geometry instanceof index_1.Polygon)) {
throw new TypeError(`"geometry" must be of type Polygon or MultiPolygon. Received type ${typeof val.geometry}`);

@@ -133,7 +134,10 @@ }

function isQueryCommand(object) {
return object && object instanceof QueryCommand && object._internalType === symbol_1.SYMBOL_QUERY_COMMAND;
return (object &&
object instanceof QueryCommand &&
object._internalType === symbol_1.SYMBOL_QUERY_COMMAND);
}
exports.isQueryCommand = isQueryCommand;
function isKnownQueryCommand(object) {
return isQueryCommand(object) && object.operator.toUpperCase() in QUERY_COMMANDS_LITERAL;
return (isQueryCommand(object) &&
object.operator.toUpperCase() in QUERY_COMMANDS_LITERAL);
}

@@ -140,0 +144,0 @@ exports.isKnownQueryCommand = isKnownQueryCommand;

@@ -42,9 +42,12 @@ "use strict";

function isUpdateCommand(object) {
return object && (object instanceof UpdateCommand) && (object._internalType === symbol_1.SYMBOL_UPDATE_COMMAND);
return (object &&
object instanceof UpdateCommand &&
object._internalType === symbol_1.SYMBOL_UPDATE_COMMAND);
}
exports.isUpdateCommand = isUpdateCommand;
function isKnownUpdateCommand(object) {
return isUpdateCommand(object) && (object.operator.toUpperCase() in UPDATE_COMMANDS_LITERAL);
return (isUpdateCommand(object) &&
object.operator.toUpperCase() in UPDATE_COMMANDS_LITERAL);
}
exports.isKnownUpdateCommand = isKnownUpdateCommand;
exports.default = UpdateCommand;

@@ -90,2 +90,2 @@ /**

}
export { ErrorCode, FieldType, WhereFilterOp, WhereFilterOpList, Operator, OperatorMap, OrderByDirection, OrderDirectionList, UpdateOperatorList, ActionType };
export { ErrorCode, FieldType, WhereFilterOp, WhereFilterOpList, Operator, OperatorMap, OrderByDirection, OrderDirectionList, UpdateOperatorList, ActionType, };

@@ -43,3 +43,3 @@ "use strict";

ObjectId: 'ObjectId',
Binary: 'Binary'
Binary: 'Binary',
};

@@ -78,3 +78,3 @@ exports.FieldType = FieldType;

[Operator.gt]: '$gt',
[Operator.gte]: '$gte'
[Operator.gte]: '$gte',
};

@@ -93,3 +93,3 @@ exports.OperatorMap = OperatorMap;

'$each',
'$position'
'$position',
];

@@ -96,0 +96,0 @@ exports.UpdateOperatorList = UpdateOperatorList;

@@ -46,3 +46,3 @@ import { Db } from './index';

*/
set(data: Object): Promise<UpdateRes>;
set(data: object): Promise<UpdateRes>;
/**

@@ -53,3 +53,3 @@ * 更新数据

*/
update(data: Object): Promise<UpdateRes>;
update(data: object): Promise<UpdateRes>;
/**

@@ -56,0 +56,0 @@ * 删除文档

@@ -35,6 +35,5 @@ "use strict";

data: datatype_1.serialize(data),
multi: (_b = options === null || options === void 0 ? void 0 : options.multi) !== null && _b !== void 0 ? _b : false
multi: (_b = options === null || options === void 0 ? void 0 : options.multi) !== null && _b !== void 0 ? _b : false,
};
const res = await this._query
.send(constant_1.ActionType.add, params);
const res = await this._query.send(constant_1.ActionType.add, params);
if (res.error) {

@@ -47,3 +46,3 @@ return {

insertedCount: undefined,
code: res.code
code: res.code,
};

@@ -55,3 +54,3 @@ }

requestId: res.requestId,
ok: true
ok: true,
};

@@ -73,3 +72,3 @@ }

if (typeof objs === 'object') {
for (let key in objs) {
for (const key in objs) {
if (objs[key] instanceof update_1.UpdateCommand) {

@@ -148,3 +147,3 @@ hasOperator = true;

keys,
options
options,
};

@@ -155,4 +154,3 @@ const params = {

};
const res = await this._query
.send(constant_1.ActionType.createIndex, params);
const res = await this._query.send(constant_1.ActionType.createIndex, params);
if (res.error) {

@@ -178,4 +176,3 @@ return {

};
const res = await this._query
.send(constant_1.ActionType.dropIndex, params);
const res = await this._query.send(constant_1.ActionType.dropIndex, params);
if (res.error) {

@@ -201,4 +198,3 @@ return {

};
const res = await this._query
.send(constant_1.ActionType.listIndexes, params);
const res = await this._query.send(constant_1.ActionType.listIndexes, params);
if (res.error) {

@@ -210,3 +206,3 @@ return {

code: res.code,
list: res.data.list
list: res.data.list,
};

@@ -213,0 +209,0 @@ }

@@ -24,3 +24,3 @@ "use strict";

}
points.forEach(point => {
points.forEach((point) => {
if (!(point instanceof point_1.Point)) {

@@ -36,4 +36,4 @@ throw new TypeError(`"points" must be of type Point[]. Received type ${typeof point}[]`);

type: 'LineString',
coordinates: this.points.map(point => point.toJSON().coordinates)
}
coordinates: this.points.map((point) => point.toJSON().coordinates),
},
};

@@ -44,3 +44,3 @@ }

type: 'LineString',
coordinates: this.points.map(point => point.toJSON().coordinates)
coordinates: this.points.map((point) => point.toJSON().coordinates),
};

@@ -52,3 +52,3 @@ }

}
for (let point of lineString.coordinates) {
for (const point of lineString.coordinates) {
if (!type_1.isNumber(point[0]) || !type_1.isNumber(point[1])) {

@@ -63,3 +63,4 @@ return false;

const lastPoint = lineString.points[lineString.points.length - 1];
if (firstPoint.latitude === lastPoint.latitude && firstPoint.longitude === lastPoint.longitude) {
if (firstPoint.latitude === lastPoint.latitude &&
firstPoint.longitude === lastPoint.longitude) {
return true;

@@ -66,0 +67,0 @@ }

@@ -24,3 +24,3 @@ "use strict";

}
lines.forEach(line => {
lines.forEach((line) => {
if (!(line instanceof lineString_1.LineString)) {

@@ -36,6 +36,6 @@ throw new TypeError(`"lines" must be of type LineString[]. Received type ${typeof line}[]`);

type: 'MultiLineString',
coordinates: this.lines.map(line => {
return line.points.map(point => [point.longitude, point.latitude]);
})
}
coordinates: this.lines.map((line) => {
return line.points.map((point) => [point.longitude, point.latitude]);
}),
},
};

@@ -46,13 +46,14 @@ }

type: 'MultiLineString',
coordinates: this.lines.map(line => {
return line.points.map(point => [point.longitude, point.latitude]);
})
coordinates: this.lines.map((line) => {
return line.points.map((point) => [point.longitude, point.latitude]);
}),
};
}
static validate(multiLineString) {
if (multiLineString.type !== 'MultiLineString' || !type_1.isArray(multiLineString.coordinates)) {
if (multiLineString.type !== 'MultiLineString' ||
!type_1.isArray(multiLineString.coordinates)) {
return false;
}
for (let line of multiLineString.coordinates) {
for (let point of line) {
for (const line of multiLineString.coordinates) {
for (const point of line) {
if (!type_1.isNumber(point[0]) || !type_1.isNumber(point[1])) {

@@ -59,0 +60,0 @@ return false;

@@ -24,3 +24,3 @@ "use strict";

}
points.forEach(point => {
points.forEach((point) => {
if (!(point instanceof point_1.Point)) {

@@ -36,4 +36,4 @@ throw new TypeError(`"points" must be of type Point[]. Received type ${typeof point}[]`);

type: 'MultiPoint',
coordinates: this.points.map(point => point.toJSON().coordinates)
}
coordinates: this.points.map((point) => point.toJSON().coordinates),
},
};

@@ -44,3 +44,3 @@ }

type: 'MultiPoint',
coordinates: this.points.map(point => point.toJSON().coordinates)
coordinates: this.points.map((point) => point.toJSON().coordinates),
};

@@ -52,3 +52,3 @@ }

}
for (let point of multiPoint.coordinates) {
for (const point of multiPoint.coordinates) {
if (!type_1.isNumber(point[0]) || !type_1.isNumber(point[1])) {

@@ -55,0 +55,0 @@ return false;

@@ -24,3 +24,3 @@ "use strict";

}
for (let polygon of polygons) {
for (const polygon of polygons) {
if (!(polygon instanceof polygon_1.Polygon)) {

@@ -36,8 +36,8 @@ throw new TypeError(`"polygon" must be of type Polygon[]. Received type ${typeof polygon}[]`);

type: 'MultiPolygon',
coordinates: this.polygons.map(polygon => {
return polygon.lines.map(line => {
return line.points.map(point => [point.longitude, point.latitude]);
coordinates: this.polygons.map((polygon) => {
return polygon.lines.map((line) => {
return line.points.map((point) => [point.longitude, point.latitude]);
});
})
}
}),
},
};

@@ -48,16 +48,17 @@ }

type: 'MultiPolygon',
coordinates: this.polygons.map(polygon => {
return polygon.lines.map(line => {
return line.points.map(point => [point.longitude, point.latitude]);
coordinates: this.polygons.map((polygon) => {
return polygon.lines.map((line) => {
return line.points.map((point) => [point.longitude, point.latitude]);
});
})
}),
};
}
static validate(multiPolygon) {
if (multiPolygon.type !== 'MultiPolygon' || !type_1.isArray(multiPolygon.coordinates)) {
if (multiPolygon.type !== 'MultiPolygon' ||
!type_1.isArray(multiPolygon.coordinates)) {
return false;
}
for (let polygon of multiPolygon.coordinates) {
for (let line of polygon) {
for (let point of line) {
for (const polygon of multiPolygon.coordinates) {
for (const line of polygon) {
for (const point of line) {
if (!type_1.isNumber(point[0]) || !type_1.isNumber(point[1])) {

@@ -64,0 +65,0 @@ return false;

@@ -28,4 +28,4 @@ "use strict";

type: 'Point',
coordinates: [this.longitude, this.latitude]
}
coordinates: [this.longitude, this.latitude],
},
};

@@ -36,6 +36,3 @@ }

type: 'Point',
coordinates: [
this.longitude,
this.latitude,
],
coordinates: [this.longitude, this.latitude],
};

@@ -47,6 +44,6 @@ }

static validate(point) {
return point.type === 'Point' &&
return (point.type === 'Point' &&
type_1.isArray(point.coordinates) &&
validate_1.Validate.isGeopoint('longitude', point.coordinates[0]) &&
validate_1.Validate.isGeopoint('latitude', point.coordinates[1]);
validate_1.Validate.isGeopoint('latitude', point.coordinates[1]));
}

@@ -53,0 +50,0 @@ get _internalType() {

@@ -24,3 +24,3 @@ "use strict";

}
lines.forEach(line => {
lines.forEach((line) => {
if (!(line instanceof lineString_1.LineString)) {

@@ -30,3 +30,3 @@ throw new TypeError(`"lines" must be of type LineString[]. Received type ${typeof line}[]`);

if (!lineString_1.LineString.isClosed(line)) {
throw new Error(`LineString ${line.points.map(p => p.toReadableString())} is not a closed cycle`);
throw new Error(`LineString ${line.points.map((p) => p.toReadableString())} is not a closed cycle`);
}

@@ -40,6 +40,6 @@ });

type: 'Polygon',
coordinates: this.lines.map(line => {
return line.points.map(point => [point.longitude, point.latitude]);
})
}
coordinates: this.lines.map((line) => {
return line.points.map((point) => [point.longitude, point.latitude]);
}),
},
};

@@ -50,5 +50,5 @@ }

type: 'Polygon',
coordinates: this.lines.map(line => {
return line.points.map(point => [point.longitude, point.latitude]);
})
coordinates: this.lines.map((line) => {
return line.points.map((point) => [point.longitude, point.latitude]);
}),
};

@@ -60,7 +60,7 @@ }

}
for (let line of polygon.coordinates) {
for (const line of polygon.coordinates) {
if (!this.isCloseLineString(line)) {
return false;
}
for (let point of line) {
for (const point of line) {
if (!type_1.isNumber(point[0]) || !type_1.isNumber(point[1])) {

@@ -67,0 +67,0 @@ return false;

@@ -10,3 +10,3 @@ import * as Geo from './geo/index';

* 地理位置类型
*/
*/
interface GeoType {

@@ -13,0 +13,0 @@ Point: typeof Geo.Point;

@@ -1,2 +0,2 @@

import { ActionType, OrderByDirection } from "./constant";
import { ActionType, OrderByDirection } from './constant';
export interface ResponseStruct {

@@ -28,3 +28,3 @@ code: number;

*/
query?: Object;
query?: object;
order?: QueryOrder[];

@@ -31,0 +31,0 @@ offset?: number;

@@ -84,3 +84,3 @@ import { ActionType, OrderByDirection } from './constant';

*/
constructor(db: Db, coll: string, fieldFilters?: Object, fieldOrders?: QueryOrder[], queryOptions?: QueryOption, withs?: WithParam[]);
constructor(db: Db, coll: string, fieldFilters?: object, fieldOrders?: QueryOrder[], queryOptions?: QueryOption, withs?: WithParam[]);
/**

@@ -178,3 +178,3 @@ * 查询条件

*/
update(data: Object, options?: {
update(data: object, options?: {
multi?: boolean;

@@ -196,4 +196,4 @@ merge?: boolean;

/**
* 发起请求获取文档列表
*/
* 发起请求获取文档列表
*/
protected internalGet<T = any>(): Promise<GetRes<T>>;

@@ -200,0 +200,0 @@ /**

@@ -42,3 +42,3 @@ "use strict";

const keys = Object.keys(query);
const checkFlag = keys.some(item => {
const checkFlag = keys.some((item) => {
return query[item] !== undefined;

@@ -63,3 +63,3 @@ });

field: fieldPath,
direction: directionStr
direction: directionStr,
};

@@ -81,3 +81,3 @@ const combinedOrders = this._fieldOrders.concat(newOrder);

as: (_a = param.as) !== null && _a !== void 0 ? _a : param.query._coll,
one: (_b = param.one) !== null && _b !== void 0 ? _b : false
one: (_b = param.one) !== null && _b !== void 0 ? _b : false,
};

@@ -99,3 +99,3 @@ const combinedWiths = this._withs.concat(newWith);

as: (_a = param.as) !== null && _a !== void 0 ? _a : param.query._coll,
one: true
one: true,
};

@@ -113,4 +113,4 @@ const combinedWiths = this._withs.concat(newWith);

if (projection instanceof Array) {
let result = {};
for (let k of projection) {
const result = {};
for (const k of projection) {
result[k] = 1;

@@ -121,3 +121,3 @@ }

else {
for (let k in projection) {
for (const k in projection) {
if (projection[k]) {

@@ -144,3 +144,3 @@ if (typeof projection[k] !== 'object') {

validate_1.Validate.isInteger('limit', limit);
let option = Object.assign({}, this._queryOptions);
const option = Object.assign({}, this._queryOptions);
option.limit = limit;

@@ -156,3 +156,3 @@ return new Query(this._db, this._coll, this._fieldFilters, this._fieldOrders, option, this._withs);

validate_1.Validate.isInteger('offset', offset);
let option = Object.assign({}, this._queryOptions);
const option = Object.assign({}, this._queryOptions);
option.offset = offset;

@@ -168,5 +168,3 @@ return new Query(this._db, this._coll, this._fieldFilters, this._fieldOrders, option, this._withs);

const size = (options === null || options === void 0 ? void 0 : options.size) || 10;
const query = this
.skip((current - 1) * size)
.limit(size);
const query = this.skip((current - 1) * size).limit(size);
query._queryOptions.count = true;

@@ -211,3 +209,3 @@ return query;

data: null,
requestId: res.requestId
requestId: res.requestId,
};

@@ -218,3 +216,3 @@ }

data: res.data[0],
requestId: res.requestId
requestId: res.requestId,
};

@@ -249,3 +247,3 @@ }

total: undefined,
code: res.code
code: res.code,
};

@@ -256,3 +254,3 @@ }

total: res.data.total,
ok: true
ok: true,
};

@@ -292,3 +290,3 @@ }

matched: undefined,
upsertId: undefined
upsertId: undefined,
};

@@ -301,3 +299,3 @@ }

upsertId: res.data.upsert_id,
ok: true
ok: true,
};

@@ -325,3 +323,3 @@ }

deleted: undefined,
code: res.code
code: res.code,
};

@@ -332,3 +330,3 @@ }

deleted: res.data.deleted,
ok: true
ok: true,
};

@@ -355,3 +353,4 @@ }

if (this._queryOptions.limit) {
param.limit = this._queryOptions.limit < 1000 ? this._queryOptions.limit : 1000;
param.limit =
this._queryOptions.limit < 1000 ? this._queryOptions.limit : 1000;
}

@@ -370,4 +369,4 @@ else {

/**
* 发起请求获取文档列表
*/
* 发起请求获取文档列表
*/
async internalGet() {

@@ -383,3 +382,3 @@ var _a, _b, _c;

ok: false,
code: res.code
code: res.code,
};

@@ -391,3 +390,3 @@ }

requestId: res.requestId,
ok: true
ok: true,
};

@@ -420,11 +419,11 @@ if (res.total)

// 针对每一个 WithParam 做合并处理
for (let _with of this._withs) {
for (const _with of this._withs) {
const { query, localField, foreignField, as, one } = _with;
const localValues = res.data.map(localData => localData[localField]);
const localValues = res.data.map((localData) => localData[localField]);
// 处理子查询
let q = query.clone();
const q = query.clone();
if (!q._fieldFilters) {
q._fieldFilters = {};
}
q._fieldFilters[foreignField] = { '$in': localValues };
q._fieldFilters[foreignField] = { $in: localValues };
// 执行子查询

@@ -444,3 +443,3 @@ let r_sub;

const _map = {};
for (let sub of r_sub.data) {
for (const sub of r_sub.data) {
const key = sub[foreignField]; // 将子表结果的连接键的值做为映射表的 key

@@ -457,3 +456,3 @@ if (one) {

const results = [];
for (let m of res.data) {
for (const m of res.data) {
// 此处主表结果中的 [value of `localField`] 与 上面子表结果中的 [value of `foreignField`] 应该是一致的

@@ -460,0 +459,0 @@ const key = m[localField];

@@ -18,3 +18,3 @@ "use strict";

$regex: this.$regex,
$options: this.$options
$options: this.$options,
};

@@ -21,0 +21,0 @@ }

@@ -14,3 +14,3 @@ interface BaseResult {

export interface GetOneRes<T> extends BaseResult {
data: T;
data: T | null;
}

@@ -17,0 +17,0 @@ export interface UpdateRes extends BaseResult {

@@ -17,10 +17,4 @@ "use strict";

}
const newParents = [
...parents,
key,
];
const newVisited = [
...visited,
value,
];
const newParents = [...parents, key];
const newVisited = [...visited, value];
const flattenedChild = flatten(value, shouldPreserverObject, newParents, newVisited);

@@ -91,3 +85,7 @@ cloned[key] = flattenedChild;

function isConversionRequired(val) {
return type_1.isInternalObject(val) || type_1.isDate(val) || type_1.isRegExp(val) || type_1.isObjectId(val) || type_1.isBinary(val);
return (type_1.isInternalObject(val) ||
type_1.isDate(val) ||
type_1.isRegExp(val) ||
type_1.isObjectId(val) ||
type_1.isBinary(val));
}

@@ -94,0 +92,0 @@ exports.isConversionRequired = isConversionRequired;

@@ -34,10 +34,7 @@ "use strict";

else if (type_1.isArray(val)) {
return val.map(item => {
return val.map((item) => {
if (visited.indexOf(item) > -1) {
throw new Error('Cannot convert circular structure to JSON');
}
return serializeHelper(item, [
...visited,
item,
]);
return serializeHelper(item, [...visited, item]);
});

@@ -51,6 +48,3 @@ }

}
ret[key] = serializeHelper(ret[key], [
...visited,
ret[key],
]);
ret[key] = serializeHelper(ret[key], [...visited, ret[key]]);
}

@@ -84,3 +78,5 @@ return ret;

// GeoPoint
if (type_1.isArray(ret.coordinates) && type_1.isNumber(ret.coordinates[0]) && type_1.isNumber(ret.coordinates[1])) {
if (type_1.isArray(ret.coordinates) &&
type_1.isNumber(ret.coordinates[0]) &&
type_1.isNumber(ret.coordinates[1])) {
return new index_1.Point(ret.coordinates[0], ret.coordinates[1]);

@@ -87,0 +83,0 @@ }

@@ -43,3 +43,3 @@ "use strict";

$regex: query.source,
$options: query.flags
$options: query.flags,
};

@@ -53,5 +53,5 @@ }

const $op = operator_map_1.operatorToString(query.operator);
const subqueries = query.operands.map(oprand => this.encodeQuery(oprand, query.fieldName));
const subqueries = query.operands.map((oprand) => this.encodeQuery(oprand, query.fieldName));
return {
[$op]: subqueries
[$op]: subqueries,
};

@@ -65,4 +65,4 @@ }

[query.fieldName]: {
[$op]: this.encodeRegExp(operatorExpression)
}
[$op]: this.encodeRegExp(operatorExpression),
},
};

@@ -74,4 +74,4 @@ }

[query.fieldName]: {
[$op]: subqueries
}
[$op]: subqueries,
},
};

@@ -85,3 +85,3 @@ }

return {
[$op]: subquery
[$op]: subquery,
};

@@ -92,3 +92,3 @@ }

return {
[$op]: subqueries
[$op]: subqueries,
};

@@ -126,4 +126,4 @@ }

[query.fieldName]: {
[$op]: common_1.encodeInternalDataType(query.operands[0])
}
[$op]: common_1.encodeInternalDataType(query.operands[0]),
},
};

@@ -136,4 +136,4 @@ }

[query.fieldName]: {
[$op]: common_1.encodeInternalDataType(query.operands)
}
[$op]: common_1.encodeInternalDataType(query.operands),
},
};

@@ -148,5 +148,5 @@ }

$maxDistance: options.maxDistance,
$minDistance: options.minDistance
}
}
$minDistance: options.minDistance,
},
},
};

@@ -159,5 +159,5 @@ }

$geoWithin: {
$geometry: options.geometry.toJSON()
}
}
$geometry: options.geometry.toJSON(),
},
},
};

@@ -170,5 +170,5 @@ }

$geoIntersects: {
$geometry: options.geometry.toJSON()
}
}
$geometry: options.geometry.toJSON(),
},
},
};

@@ -179,4 +179,4 @@ }

[query.fieldName]: {
[$op]: common_1.encodeInternalDataType(query.operands[0])
}
[$op]: common_1.encodeInternalDataType(query.operands[0]),
},
};

@@ -183,0 +183,0 @@ }

@@ -50,4 +50,4 @@ "use strict";

[$op]: {
[query.fieldName]: ''
}
[query.fieldName]: '',
},
};

@@ -58,4 +58,4 @@ }

[$op]: {
[query.fieldName]: query.operands[0]
}
[query.fieldName]: query.operands[0],
},
};

@@ -72,3 +72,3 @@ }

modifiers = {
$each: query.operands.map(common_1.encodeInternalDataType)
$each: query.operands.map(common_1.encodeInternalDataType),
};

@@ -81,4 +81,4 @@ }

[$op]: {
[query.fieldName]: modifiers
}
[query.fieldName]: modifiers,
},
};

@@ -89,8 +89,8 @@ }

$each: query.operands.map(common_1.encodeInternalDataType),
$position: 0
$position: 0,
};
return {
[$op]: {
[query.fieldName]: modifiers
}
[query.fieldName]: modifiers,
},
};

@@ -101,4 +101,4 @@ }

[$op]: {
[query.fieldName]: 1
}
[query.fieldName]: 1,
},
};

@@ -109,4 +109,4 @@ }

[$op]: {
[query.fieldName]: -1
}
[query.fieldName]: -1,
},
};

@@ -117,4 +117,4 @@ }

[$op]: {
[query.fieldName]: common_1.encodeInternalDataType(query.operands)
}
[query.fieldName]: common_1.encodeInternalDataType(query.operands),
},
};

@@ -121,0 +121,0 @@ }

@@ -14,4 +14,4 @@ "use strict";

$date: {
offset: this.offset
}
offset: this.offset,
},
};

@@ -18,0 +18,0 @@ }

@@ -20,4 +20,4 @@ interface DocumentModel {

*/
static whichType: (obj: any) => String;
static whichType: (obj: any) => string;
}
export {};

@@ -20,3 +20,3 @@ "use strict";

Util.formatResDocumentData = (documents) => {
return documents.map(document => {
return documents.map((document) => {
return Util.formatField(document);

@@ -33,3 +33,3 @@ });

*/
Util.formatField = document => {
Util.formatField = (document) => {
const keys = Object.keys(document);

@@ -41,3 +41,3 @@ let protoField = {};

}
keys.forEach(key => {
keys.forEach((key) => {
const item = document[key];

@@ -51,15 +51,15 @@ const type = Util.whichType(item);

case constant_1.FieldType.GeoLineString:
realValue = new index_1.LineString(item.coordinates.map(point => new index_1.Point(point[0], point[1])));
realValue = new index_1.LineString(item.coordinates.map((point) => new index_1.Point(point[0], point[1])));
break;
case constant_1.FieldType.GeoPolygon:
realValue = new index_1.Polygon(item.coordinates.map(line => new index_1.LineString(line.map(([lng, lat]) => new index_1.Point(lng, lat)))));
realValue = new index_1.Polygon(item.coordinates.map((line) => new index_1.LineString(line.map(([lng, lat]) => new index_1.Point(lng, lat)))));
break;
case constant_1.FieldType.GeoMultiPoint:
realValue = new index_1.MultiPoint(item.coordinates.map(point => new index_1.Point(point[0], point[1])));
realValue = new index_1.MultiPoint(item.coordinates.map((point) => new index_1.Point(point[0], point[1])));
break;
case constant_1.FieldType.GeoMultiLineString:
realValue = new index_1.MultiLineString(item.coordinates.map(line => new index_1.LineString(line.map(([lng, lat]) => new index_1.Point(lng, lat)))));
realValue = new index_1.MultiLineString(item.coordinates.map((line) => new index_1.LineString(line.map(([lng, lat]) => new index_1.Point(lng, lat)))));
break;
case constant_1.FieldType.GeoMultiPolygon:
realValue = new index_1.MultiPolygon(item.coordinates.map(polygon => new index_1.Polygon(polygon.map(line => new index_1.LineString(line.map(([lng, lat]) => new index_1.Point(lng, lat)))))));
realValue = new index_1.MultiPolygon(item.coordinates.map((polygon) => new index_1.Polygon(polygon.map((line) => new index_1.LineString(line.map(([lng, lat]) => new index_1.Point(lng, lat)))))));
break;

@@ -66,0 +66,0 @@ case constant_1.FieldType.Timestamp:

@@ -18,3 +18,3 @@ "use strict";

*/
exports.isInternalObject = (x) => x && (x._internalType instanceof symbol_1.InternalSymbol);
exports.isInternalObject = (x) => x && x._internalType instanceof symbol_1.InternalSymbol;
exports.isPlainObject = (obj) => {

@@ -21,0 +21,0 @@ if (typeof obj !== 'object' || obj === null)

@@ -5,3 +5,3 @@ "use strict";

const type_1 = require("./type");
exports.sleep = (ms = 0) => new Promise(r => setTimeout(r, ms));
exports.sleep = (ms = 0) => new Promise((r) => setTimeout(r, ms));
const counters = {};

@@ -15,3 +15,3 @@ exports.autoCount = (domain = 'any') => {

// 递归过滤对象中的undefiend字段
exports.filterUndefined = o => {
exports.filterUndefined = (o) => {
// 如果不是对象类型,直接返回

@@ -21,3 +21,3 @@ if (!type_1.isObject(o)) {

}
for (let key in o) {
for (const key in o) {
if (o[key] === undefined) {

@@ -32,3 +32,3 @@ delete o[key];

};
exports.stringifyByEJSON = params => {
exports.stringifyByEJSON = (params) => {
// params中删除undefined的key

@@ -38,4 +38,4 @@ params = exports.filterUndefined(params);

};
exports.parseByEJSON = params => {
exports.parseByEJSON = (params) => {
return bson_1.EJSON.parse(params);
};

@@ -14,8 +14,8 @@ "use strict";

/**
*
* @static
* @param {StageName:{}|string} stage
* @returns {Boolean}
* @memberof Validate
*/
*
* @static
* @param {StageName:{}|string} stage
* @returns {Boolean}
* @memberof Validate
*/
static isValidAggregation(stage) {

@@ -83,3 +83,3 @@ if (Object.keys(stage).length !== 1) {

}
for (let key in value) {
for (const key in value) {
const subValue = value[key];

@@ -86,0 +86,0 @@ if (subValue !== 1 && subValue !== -1) {

@@ -76,3 +76,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

collectionName: this._collectionName,
stages: this._stages
stages: this._stages,
})];

@@ -87,3 +87,3 @@ case 1:

ok: false,
code: res.code
code: res.code,
}];

@@ -95,3 +95,3 @@ }

requestId: res.requestId,
ok: true
ok: true,
};

@@ -127,3 +127,3 @@ return [2 /*return*/, result];

stageKey: raw ? stage : "$" + stage,
stageValue: transformParam
stageValue: transformParam,
});

@@ -149,3 +149,4 @@ return this;

// 判断是否有 distanceMultiplier 参数
if (param.distanceMultiplier && typeof (param.distanceMultiplier) === 'number') {
if (param.distanceMultiplier &&
typeof param.distanceMultiplier === 'number') {
param.distanceMultiplier = param.distanceMultiplier * EARTH_RADIUS;

@@ -152,0 +153,0 @@ }

@@ -25,3 +25,3 @@ import { DocumentReference } from './document';

*/
add(data: Object, options?: {
add(data: object, options?: {
multi: boolean;

@@ -28,0 +28,0 @@ }): Promise<import("./result-types").AddRes>;

@@ -1,2 +0,3 @@

import { QueryCommand, QUERY_COMMANDS_LITERAL } from './commands/query';
/* eslint-disable prefer-rest-params */
import { QueryCommand, QUERY_COMMANDS_LITERAL, } from './commands/query';
import { LogicCommand, LOGIC_COMMANDS_LITERAL } from './commands/logic';

@@ -63,3 +64,5 @@ import { UpdateCommand, UPDATE_COMMANDS_LITERAL } from './commands/update';

}
var expressions = isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
var expressions = isArray(arguments[0])
? arguments[0]
: Array.from(arguments);
return new LogicCommand(LOGIC_COMMANDS_LITERAL.AND, expressions);

@@ -72,3 +75,5 @@ },

}
var expressions = isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
var expressions = isArray(arguments[0])
? arguments[0]
: Array.from(arguments);
return new LogicCommand(LOGIC_COMMANDS_LITERAL.NOR, expressions);

@@ -81,3 +86,5 @@ },

}
var expressions = isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
var expressions = isArray(arguments[0])
? arguments[0]
: Array.from(arguments);
return new LogicCommand(LOGIC_COMMANDS_LITERAL.OR, expressions);

@@ -90,3 +97,5 @@ },

}
var expressions = isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
var expressions = isArray(arguments[0])
? arguments[0]
: Array.from(arguments);
return new LogicCommand(LOGIC_COMMANDS_LITERAL.NOT, expressions);

@@ -118,3 +127,3 @@ },

$sort: options.sort,
$slice: options.slice
$slice: options.slice,
};

@@ -167,3 +176,3 @@ }

return {
$expr: values
$expr: values,
};

@@ -173,3 +182,3 @@ },

return {
$jsonSchema: schema
$jsonSchema: schema,
};

@@ -180,3 +189,3 @@ },

return {
$search: values.search
$search: values.search,
};

@@ -189,3 +198,3 @@ }

$caseSensitive: values.caseSensitive,
$diacriticSensitive: values.diacriticSensitive
$diacriticSensitive: values.diacriticSensitive,
};

@@ -269,7 +278,11 @@ }

// 集合操作符(7个)
allElementsTrue: function (param) { return new AggregationOperator('allElementsTrue', param); },
allElementsTrue: function (param) {
return new AggregationOperator('allElementsTrue', param);
},
anyElementTrue: function (param) { return new AggregationOperator('anyElementTrue', param); },
setDifference: function (param) { return new AggregationOperator('setDifference', param); },
setEquals: function (param) { return new AggregationOperator('setEquals', param); },
setIntersection: function (param) { return new AggregationOperator('setIntersection', param); },
setIntersection: function (param) {
return new AggregationOperator('setIntersection', param);
},
setIsSubset: function (param) { return new AggregationOperator('setIsSubset', param); },

@@ -309,8 +322,8 @@ setUnion: function (param) { return new AggregationOperator('setUnion', param); },

// 变量声明操作符
let: function (param) { return new AggregationOperator('let', param); }
let: function (param) { return new AggregationOperator('let', param); },
},
project: {
slice: function (param) { return new ProjectionOperator('slice', param); },
elemMatch: function (param) { return new ProjectionOperator('elemMatch', param); }
}
elemMatch: function (param) { return new ProjectionOperator('elemMatch', param); },
},
};

@@ -317,0 +330,0 @@ var AggregationOperator = /** @class */ (function () {

@@ -1,2 +0,3 @@

import { SYMBOL_UNSET_FIELD_NAME, SYMBOL_LOGIC_COMMAND } from '../helper/symbol';
/* eslint-disable prefer-rest-params */
import { SYMBOL_UNSET_FIELD_NAME, SYMBOL_LOGIC_COMMAND, } from '../helper/symbol';
import { isQueryCommand } from './query';

@@ -92,3 +93,5 @@ export var AND = 'and';

}
var expressions = Array.isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
var expressions = Array.isArray(arguments[0])
? arguments[0]
: Array.from(arguments);
expressions.unshift(this);

@@ -106,3 +109,5 @@ return new LogicCommand(LOGIC_COMMANDS_LITERAL.AND, expressions, this.fieldName);

}
var expressions = Array.isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
var expressions = Array.isArray(arguments[0])
? arguments[0]
: Array.from(arguments);
expressions.unshift(this);

@@ -115,7 +120,9 @@ return new LogicCommand(LOGIC_COMMANDS_LITERAL.OR, expressions, this.fieldName);

export function isLogicCommand(object) {
return object && (object instanceof LogicCommand) && (object._internalType === SYMBOL_LOGIC_COMMAND);
return (object &&
object instanceof LogicCommand &&
object._internalType === SYMBOL_LOGIC_COMMAND);
}
export function isKnownLogicCommand(object) {
return isLogicCommand && (object.operator.toUpperCase() in LOGIC_COMMANDS_LITERAL);
return (isLogicCommand && object.operator.toUpperCase() in LOGIC_COMMANDS_LITERAL);
}
export default LogicCommand;

@@ -16,3 +16,3 @@ var __extends = (this && this.__extends) || (function () {

import { SYMBOL_QUERY_COMMAND } from '../helper/symbol';
import { Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon } from '../geo/index';
import { Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, } from '../geo/index';
import { isNumber } from '../utils/type';

@@ -125,3 +125,4 @@ export var EQ = 'eq';

QueryCommand.prototype.geoWithin = function (val) {
if (!(val.geometry instanceof MultiPolygon) && !(val.geometry instanceof Polygon)) {
if (!(val.geometry instanceof MultiPolygon) &&
!(val.geometry instanceof Polygon)) {
throw new TypeError("\"geometry\" must be of type Polygon or MultiPolygon. Received type " + typeof val.geometry);

@@ -148,6 +149,9 @@ }

export function isQueryCommand(object) {
return object && object instanceof QueryCommand && object._internalType === SYMBOL_QUERY_COMMAND;
return (object &&
object instanceof QueryCommand &&
object._internalType === SYMBOL_QUERY_COMMAND);
}
export function isKnownQueryCommand(object) {
return isQueryCommand(object) && object.operator.toUpperCase() in QUERY_COMMANDS_LITERAL;
return (isQueryCommand(object) &&
object.operator.toUpperCase() in QUERY_COMMANDS_LITERAL);
}

@@ -154,0 +158,0 @@ export function isComparisonCommand(object) {

@@ -1,2 +0,2 @@

import { SYMBOL_UNSET_FIELD_NAME, SYMBOL_UPDATE_COMMAND } from '../helper/symbol';
import { SYMBOL_UNSET_FIELD_NAME, SYMBOL_UPDATE_COMMAND, } from '../helper/symbol';
export var UPDATE_COMMANDS_LITERAL;

@@ -41,7 +41,10 @@ (function (UPDATE_COMMANDS_LITERAL) {

export function isUpdateCommand(object) {
return object && (object instanceof UpdateCommand) && (object._internalType === SYMBOL_UPDATE_COMMAND);
return (object &&
object instanceof UpdateCommand &&
object._internalType === SYMBOL_UPDATE_COMMAND);
}
export function isKnownUpdateCommand(object) {
return isUpdateCommand(object) && (object.operator.toUpperCase() in UPDATE_COMMANDS_LITERAL);
return (isUpdateCommand(object) &&
object.operator.toUpperCase() in UPDATE_COMMANDS_LITERAL);
}
export default UpdateCommand;

@@ -90,2 +90,2 @@ /**

}
export { ErrorCode, FieldType, WhereFilterOp, WhereFilterOpList, Operator, OperatorMap, OrderByDirection, OrderDirectionList, UpdateOperatorList, ActionType };
export { ErrorCode, FieldType, WhereFilterOp, WhereFilterOpList, Operator, OperatorMap, OrderByDirection, OrderDirectionList, UpdateOperatorList, ActionType, };

@@ -41,3 +41,3 @@ /**

ObjectId: 'ObjectId',
Binary: 'Binary'
Binary: 'Binary',
};

@@ -85,3 +85,3 @@ /**

'$each',
'$position'
'$position',
];

@@ -100,2 +100,2 @@ var ActionType;

})(ActionType || (ActionType = {}));
export { ErrorCode, FieldType, WhereFilterOpList, Operator, OperatorMap, OrderDirectionList, UpdateOperatorList, ActionType };
export { ErrorCode, FieldType, WhereFilterOpList, Operator, OperatorMap, OrderDirectionList, UpdateOperatorList, ActionType, };

@@ -46,3 +46,3 @@ import { Db } from './index';

*/
set(data: Object): Promise<UpdateRes>;
set(data: object): Promise<UpdateRes>;
/**

@@ -53,3 +53,3 @@ * 更新数据

*/
update(data: Object): Promise<UpdateRes>;
update(data: object): Promise<UpdateRes>;
/**

@@ -56,0 +56,0 @@ * 删除文档

@@ -74,6 +74,5 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

data: serialize(data),
multi: (_b = options === null || options === void 0 ? void 0 : options.multi) !== null && _b !== void 0 ? _b : false
multi: (_b = options === null || options === void 0 ? void 0 : options.multi) !== null && _b !== void 0 ? _b : false,
};
return [4 /*yield*/, this._query
.send(ActionType.add, params)];
return [4 /*yield*/, this._query.send(ActionType.add, params)];
case 1:

@@ -88,3 +87,3 @@ res = _c.sent();

insertedCount: undefined,
code: res.code
code: res.code,
}];

@@ -96,3 +95,3 @@ }

requestId: res.requestId,
ok: true
ok: true,
}];

@@ -236,3 +235,3 @@ }

keys: keys,
options: options
options: options,
};

@@ -243,4 +242,3 @@ params = {

};
return [4 /*yield*/, this._query
.send(ActionType.createIndex, params)];
return [4 /*yield*/, this._query.send(ActionType.createIndex, params)];
case 1:

@@ -276,4 +274,3 @@ res = _b.sent();

};
return [4 /*yield*/, this._query
.send(ActionType.dropIndex, params)];
return [4 /*yield*/, this._query.send(ActionType.dropIndex, params)];
case 1:

@@ -309,4 +306,3 @@ res = _a.sent();

};
return [4 /*yield*/, this._query
.send(ActionType.listIndexes, params)];
return [4 /*yield*/, this._query.send(ActionType.listIndexes, params)];
case 1:

@@ -320,3 +316,3 @@ res = _a.sent();

code: res.code,
list: res.data.list
list: res.data.list,
}];

@@ -323,0 +319,0 @@ }

@@ -34,3 +34,3 @@ import { SYMBOL_GEO_LINE_STRING } from '../helper/symbol';

type: 'LineString',
coordinates: this.points.map(function (point) { return point.toJSON().coordinates; })
coordinates: this.points.map(function (point) { return point.toJSON().coordinates; }),
},

@@ -42,3 +42,3 @@ _a;

type: 'LineString',
coordinates: this.points.map(function (point) { return point.toJSON().coordinates; })
coordinates: this.points.map(function (point) { return point.toJSON().coordinates; }),
};

@@ -61,3 +61,4 @@ };

var lastPoint = lineString.points[lineString.points.length - 1];
if (firstPoint.latitude === lastPoint.latitude && firstPoint.longitude === lastPoint.longitude) {
if (firstPoint.latitude === lastPoint.latitude &&
firstPoint.longitude === lastPoint.longitude) {
return true;

@@ -64,0 +65,0 @@ }

@@ -36,3 +36,3 @@ import { SYMBOL_GEO_MULTI_LINE_STRING } from '../helper/symbol';

return line.points.map(function (point) { return [point.longitude, point.latitude]; });
})
}),
},

@@ -46,7 +46,8 @@ _a;

return line.points.map(function (point) { return [point.longitude, point.latitude]; });
})
}),
};
};
MultiLineString.validate = function (multiLineString) {
if (multiLineString.type !== 'MultiLineString' || !isArray(multiLineString.coordinates)) {
if (multiLineString.type !== 'MultiLineString' ||
!isArray(multiLineString.coordinates)) {
return false;

@@ -53,0 +54,0 @@ }

@@ -34,3 +34,3 @@ import { SYMBOL_GEO_MULTI_POINT } from '../helper/symbol';

type: 'MultiPoint',
coordinates: this.points.map(function (point) { return point.toJSON().coordinates; })
coordinates: this.points.map(function (point) { return point.toJSON().coordinates; }),
},

@@ -42,3 +42,3 @@ _a;

type: 'MultiPoint',
coordinates: this.points.map(function (point) { return point.toJSON().coordinates; })
coordinates: this.points.map(function (point) { return point.toJSON().coordinates; }),
};

@@ -45,0 +45,0 @@ };

@@ -39,3 +39,3 @@ import { SYMBOL_GEO_POLYGON } from '../helper/symbol';

});
})
}),
},

@@ -51,7 +51,8 @@ _a;

});
})
}),
};
};
MultiPolygon.validate = function (multiPolygon) {
if (multiPolygon.type !== 'MultiPolygon' || !isArray(multiPolygon.coordinates)) {
if (multiPolygon.type !== 'MultiPolygon' ||
!isArray(multiPolygon.coordinates)) {
return false;

@@ -58,0 +59,0 @@ }

@@ -27,3 +27,3 @@ import { Validate } from '../validate';

type: 'Point',
coordinates: [this.longitude, this.latitude]
coordinates: [this.longitude, this.latitude],
},

@@ -35,6 +35,3 @@ _a;

type: 'Point',
coordinates: [
this.longitude,
this.latitude,
],
coordinates: [this.longitude, this.latitude],
};

@@ -46,6 +43,6 @@ };

Point.validate = function (point) {
return point.type === 'Point' &&
return (point.type === 'Point' &&
isArray(point.coordinates) &&
Validate.isGeopoint('longitude', point.coordinates[0]) &&
Validate.isGeopoint('latitude', point.coordinates[1]);
Validate.isGeopoint('latitude', point.coordinates[1]));
};

@@ -52,0 +49,0 @@ Object.defineProperty(Point.prototype, "_internalType", {

@@ -27,3 +27,5 @@ import { SYMBOL_GEO_MULTI_POLYGON } from '../helper/symbol';

if (!LineString.isClosed(line)) {
throw new Error("LineString " + line.points.map(function (p) { return p.toReadableString(); }) + " is not a closed cycle");
throw new Error("LineString " + line.points.map(function (p) {
return p.toReadableString();
}) + " is not a closed cycle");
}

@@ -40,3 +42,3 @@ });

return line.points.map(function (point) { return [point.longitude, point.latitude]; });
})
}),
},

@@ -50,3 +52,3 @@ _a;

return line.points.map(function (point) { return [point.longitude, point.latitude]; });
})
}),
};

@@ -53,0 +55,0 @@ };

@@ -10,3 +10,3 @@ import * as Geo from './geo/index';

* 地理位置类型
*/
*/
interface GeoType {

@@ -13,0 +13,0 @@ Point: typeof Geo.Point;

@@ -1,2 +0,2 @@

import { ActionType, OrderByDirection } from "./constant";
import { ActionType, OrderByDirection } from './constant';
export interface ResponseStruct {

@@ -28,3 +28,3 @@ code: number;

*/
query?: Object;
query?: object;
order?: QueryOrder[];

@@ -31,0 +31,0 @@ offset?: number;

@@ -84,3 +84,3 @@ import { ActionType, OrderByDirection } from './constant';

*/
constructor(db: Db, coll: string, fieldFilters?: Object, fieldOrders?: QueryOrder[], queryOptions?: QueryOption, withs?: WithParam[]);
constructor(db: Db, coll: string, fieldFilters?: object, fieldOrders?: QueryOrder[], queryOptions?: QueryOption, withs?: WithParam[]);
/**

@@ -178,3 +178,3 @@ * 查询条件

*/
update(data: Object, options?: {
update(data: object, options?: {
multi?: boolean;

@@ -196,4 +196,4 @@ merge?: boolean;

/**
* 发起请求获取文档列表
*/
* 发起请求获取文档列表
*/
protected internalGet<T = any>(): Promise<GetRes<T>>;

@@ -200,0 +200,0 @@ /**

@@ -114,3 +114,3 @@ var __assign = (this && this.__assign) || function () {

field: fieldPath,
direction: directionStr
direction: directionStr,
};

@@ -132,3 +132,3 @@ var combinedOrders = this._fieldOrders.concat(newOrder);

as: (_a = param.as) !== null && _a !== void 0 ? _a : param.query._coll,
one: (_b = param.one) !== null && _b !== void 0 ? _b : false
one: (_b = param.one) !== null && _b !== void 0 ? _b : false,
};

@@ -150,3 +150,3 @@ var combinedWiths = this._withs.concat(newWith);

as: (_a = param.as) !== null && _a !== void 0 ? _a : param.query._coll,
one: true
one: true,
};

@@ -216,5 +216,3 @@ var combinedWiths = this._withs.concat(newWith);

var size = (options === null || options === void 0 ? void 0 : options.size) || 10;
var query = this
.skip((current - 1) * size)
.limit(size);
var query = this.skip((current - 1) * size).limit(size);
query._queryOptions.count = true;

@@ -271,3 +269,3 @@ return query;

data: null,
requestId: res.requestId
requestId: res.requestId,
}];

@@ -278,3 +276,3 @@ }

data: res.data[0],
requestId: res.requestId
requestId: res.requestId,
}];

@@ -328,3 +326,3 @@ }

total: undefined,
code: res.code
code: res.code,
}];

@@ -335,3 +333,3 @@ }

total: res.data.total,
ok: true
ok: true,
}];

@@ -381,3 +379,3 @@ }

matched: undefined,
upsertId: undefined
upsertId: undefined,
}];

@@ -390,3 +388,3 @@ }

upsertId: res.data.upsert_id,
ok: true
ok: true,
}];

@@ -424,3 +422,3 @@ }

deleted: undefined,
code: res.code
code: res.code,
}];

@@ -431,3 +429,3 @@ }

deleted: res.data.deleted,
ok: true
ok: true,
}];

@@ -457,3 +455,4 @@ }

if (this._queryOptions.limit) {
param.limit = this._queryOptions.limit < 1000 ? this._queryOptions.limit : 1000;
param.limit =
this._queryOptions.limit < 1000 ? this._queryOptions.limit : 1000;
}

@@ -472,4 +471,4 @@ else {

/**
* 发起请求获取文档列表
*/
* 发起请求获取文档列表
*/
Query.prototype.internalGet = function () {

@@ -492,3 +491,3 @@ var _a, _b, _c;

ok: false,
code: res.code
code: res.code,
}];

@@ -500,3 +499,3 @@ }

requestId: res.requestId,
ok: true
ok: true,
};

@@ -548,3 +547,3 @@ if (res.total)

}
q._fieldFilters[foreignField] = { '$in': localValues };
q._fieldFilters[foreignField] = { $in: localValues };
r_sub = void 0;

@@ -551,0 +550,0 @@ if (!q._withs.length) return [3 /*break*/, 2];

@@ -17,3 +17,3 @@ import { SYMBOL_REGEXP } from '../helper/symbol';

$regex: this.$regex,
$options: this.$options
$options: this.$options,
};

@@ -20,0 +20,0 @@ };

@@ -14,3 +14,3 @@ interface BaseResult {

export interface GetOneRes<T> extends BaseResult {
data: T;
data: T | null;
}

@@ -17,0 +17,0 @@ export interface UpdateRes extends BaseResult {

@@ -19,4 +19,4 @@ var __assign = (this && this.__assign) || function () {

};
import { getType, isObject, isArray, isDate, isRegExp, isInternalObject, isObjectId, isBinary } from '../utils/type';
import { serialize as serializeInternalDataType, deserialize as deserializeInternalDataType } from './datatype';
import { getType, isObject, isArray, isDate, isRegExp, isInternalObject, isObjectId, isBinary, } from '../utils/type';
import { serialize as serializeInternalDataType, deserialize as deserializeInternalDataType, } from './datatype';
function flatten(query, shouldPreserverObject, parents, visited) {

@@ -34,8 +34,4 @@ var cloned = __assign({}, query);

}
var newParents = __spreadArrays(parents, [
key,
]);
var newVisited = __spreadArrays(visited, [
value,
]);
var newParents = __spreadArrays(parents, [key]);
var newVisited = __spreadArrays(visited, [value]);
var flattenedChild = flatten(value, shouldPreserverObject, newParents, newVisited);

@@ -103,3 +99,7 @@ cloned[key] = flattenedChild;

export function isConversionRequired(val) {
return isInternalObject(val) || isDate(val) || isRegExp(val) || isObjectId(val) || isBinary(val);
return (isInternalObject(val) ||
isDate(val) ||
isRegExp(val) ||
isObjectId(val) ||
isBinary(val));
}

@@ -106,0 +106,0 @@ export function encodeInternalDataType(val) {

@@ -20,4 +20,4 @@ var __assign = (this && this.__assign) || function () {

// transpile internal data type
import { SYMBOL_GEO_POINT, SYMBOL_SERVER_DATE, SYMBOL_REGEXP } from '../helper/symbol';
import { getType, isObject, isArray, isDate, isNumber, isInternalObject, isRegExp, isObjectId, isBinary } from '../utils/type';
import { SYMBOL_GEO_POINT, SYMBOL_SERVER_DATE, SYMBOL_REGEXP, } from '../helper/symbol';
import { getType, isObject, isArray, isDate, isNumber, isInternalObject, isRegExp, isObjectId, isBinary, } from '../utils/type';
import { Point } from '../geo/index';

@@ -54,5 +54,3 @@ import { ServerDate } from '../serverDate/index';

}
return serializeHelper(item, __spreadArrays(visited, [
item,
]));
return serializeHelper(item, __spreadArrays(visited, [item]));
});

@@ -66,5 +64,3 @@ }

}
ret[key] = serializeHelper(ret[key], __spreadArrays(visited, [
ret[key],
]));
ret[key] = serializeHelper(ret[key], __spreadArrays(visited, [ret[key]]));
}

@@ -98,3 +94,5 @@ return ret;

// GeoPoint
if (isArray(ret.coordinates) && isNumber(ret.coordinates[0]) && isNumber(ret.coordinates[1])) {
if (isArray(ret.coordinates) &&
isNumber(ret.coordinates[0]) &&
isNumber(ret.coordinates[1])) {
return new Point(ret.coordinates[0], ret.coordinates[1]);

@@ -101,0 +99,0 @@ }

@@ -1,7 +0,7 @@

import { isQueryCommand, isComparisonCommand, QUERY_COMMANDS_LITERAL } from '../commands/query';
import { isLogicCommand, LOGIC_COMMANDS_LITERAL } from '../commands/logic';
import { isQueryCommand, isComparisonCommand, QUERY_COMMANDS_LITERAL, } from '../commands/query';
import { isLogicCommand, LOGIC_COMMANDS_LITERAL, } from '../commands/logic';
import { SYMBOL_UNSET_FIELD_NAME } from '../helper/symbol';
import { getType, isObject, isArray, isRegExp } from '../utils/type';
import { operatorToString } from '../operator-map';
import { flattenQueryObject, isConversionRequired, encodeInternalDataType } from './common';
import { flattenQueryObject, isConversionRequired, encodeInternalDataType, } from './common';
var QuerySerializer = /** @class */ (function () {

@@ -46,3 +46,3 @@ function QuerySerializer() {

$regex: query.source,
$options: query.flags
$options: query.flags,
};

@@ -149,4 +149,4 @@ };

$maxDistance: options.maxDistance,
$minDistance: options.minDistance
}
$minDistance: options.minDistance,
},
},

@@ -160,4 +160,4 @@ _e;

$geoWithin: {
$geometry: options.geometry.toJSON()
}
$geometry: options.geometry.toJSON(),
},
},

@@ -171,4 +171,4 @@ _f;

$geoIntersects: {
$geometry: options.geometry.toJSON()
}
$geometry: options.geometry.toJSON(),
},
},

@@ -175,0 +175,0 @@ _g;

@@ -1,6 +0,6 @@

import { UpdateCommand, isUpdateCommand, UPDATE_COMMANDS_LITERAL } from '../commands/update';
import { UpdateCommand, isUpdateCommand, UPDATE_COMMANDS_LITERAL, } from '../commands/update';
import { SYMBOL_UNSET_FIELD_NAME } from '../helper/symbol';
import { getType, isArray } from '../utils/type';
import { operatorToString } from '../operator-map';
import { flattenQueryObject, encodeInternalDataType, mergeConditionAfterEncode } from './common';
import { flattenQueryObject, encodeInternalDataType, mergeConditionAfterEncode, } from './common';
var UpdateSerializer = /** @class */ (function () {

@@ -71,3 +71,3 @@ function UpdateSerializer() {

modifiers = {
$each: query.operands.map(encodeInternalDataType)
$each: query.operands.map(encodeInternalDataType),
};

@@ -87,3 +87,3 @@ }

$each: query.operands.map(encodeInternalDataType),
$position: 0
$position: 0,
};

@@ -90,0 +90,0 @@ return _c = {},

@@ -17,4 +17,4 @@ import { SYMBOL_SERVER_DATE } from '../helper/symbol';

$date: {
offset: this.offset
}
offset: this.offset,
},
};

@@ -21,0 +21,0 @@ };

@@ -20,4 +20,4 @@ interface DocumentModel {

*/
static whichType: (obj: any) => String;
static whichType: (obj: any) => string;
}
export {};
import { Binary, EJSON, ObjectId } from 'bson';
import { FieldType } from './constant';
import { Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon } from './geo/index';
import { Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, } from './geo/index';
import { ServerDate } from './serverDate/index';

@@ -49,6 +49,8 @@ /**

case FieldType.GeoPolygon:
realValue = new Polygon(item.coordinates.map(function (line) { return new LineString(line.map(function (_a) {
var lng = _a[0], lat = _a[1];
return new Point(lng, lat);
})); }));
realValue = new Polygon(item.coordinates.map(function (line) {
return new LineString(line.map(function (_a) {
var lng = _a[0], lat = _a[1];
return new Point(lng, lat);
}));
}));
break;

@@ -59,13 +61,17 @@ case FieldType.GeoMultiPoint:

case FieldType.GeoMultiLineString:
realValue = new MultiLineString(item.coordinates.map(function (line) { return new LineString(line.map(function (_a) {
var lng = _a[0], lat = _a[1];
return new Point(lng, lat);
})); }));
realValue = new MultiLineString(item.coordinates.map(function (line) {
return new LineString(line.map(function (_a) {
var lng = _a[0], lat = _a[1];
return new Point(lng, lat);
}));
}));
break;
case FieldType.GeoMultiPolygon:
realValue = new MultiPolygon(item.coordinates.map(function (polygon) {
return new Polygon(polygon.map(function (line) { return new LineString(line.map(function (_a) {
var lng = _a[0], lat = _a[1];
return new Point(lng, lat);
})); }));
return new Polygon(polygon.map(function (line) {
return new LineString(line.map(function (_a) {
var lng = _a[0], lat = _a[1];
return new Point(lng, lat);
}));
}));
}));

@@ -72,0 +78,0 @@ break;

import { InternalSymbol } from './symbol';
export var getType = function (x) { return Object.prototype.toString.call(x).slice(8, -1).toLowerCase(); };
export var isObject = function (x) { return getType(x) === 'object'; };
export var getType = function (x) {
return Object.prototype.toString.call(x).slice(8, -1).toLowerCase();
};
export var isObject = function (x) {
return getType(x) === 'object';
};
export var isString = function (x) { return getType(x) === 'string'; };
export var isNumber = function (x) { return getType(x) === 'number'; };
export var isPromise = function (x) { return getType(x) === 'promise'; };
export var isFunction = function (x) { return typeof x === 'function'; };
export var isArray = function (x) { return Array.isArray(x); };
export var isFunction = function (x) {
return typeof x === 'function';
};
export var isArray = function (x) {
return Array.isArray(x);
};
export var isDate = function (x) { return getType(x) === 'date'; };

@@ -16,3 +24,5 @@ export var isRegExp = function (x) { return getType(x) === 'regexp'; };

*/
export var isInternalObject = function (x) { return x && (x._internalType instanceof InternalSymbol); };
export var isInternalObject = function (x) {
return x && x._internalType instanceof InternalSymbol;
};
export var isPlainObject = function (obj) {

@@ -19,0 +29,0 @@ if (typeof obj !== 'object' || obj === null)

@@ -1,2 +0,2 @@

import { ErrorCode, WhereFilterOpList, OrderDirectionList, FieldType } from './constant';
import { ErrorCode, WhereFilterOpList, OrderDirectionList, FieldType, } from './constant';
import { Util } from './util';

@@ -14,8 +14,8 @@ import { getType } from './utils/type';

/**
*
* @static
* @param {StageName:{}|string} stage
* @returns {Boolean}
* @memberof Validate
*/
*
* @static
* @param {StageName:{}|string} stage
* @returns {Boolean}
* @memberof Validate
*/
Validate.isValidAggregation = function (stage) {

@@ -22,0 +22,0 @@ if (Object.keys(stage).length !== 1) {

{
"name": "database-ql",
"version": "1.0.0-beta.12",
"version": "1.0.0-beta.14",
"description": "Database interface for laf",

@@ -11,4 +11,3 @@ "main": "dist/commonjs/index.js",

"build": "tsc -p tsconfig.json && tsc -p tsconfig.esm.json",
"eslint": "eslint \"./**/*.ts\"",
"fix": "eslint --fix \"./**/*.ts\"",
"lint": "eslint . --fix --ext .ts --ext .js",
"prepublishOnly": "npm run build"

@@ -28,10 +27,5 @@ },

"devDependencies": {
"eslint": "^8.8.0",
"eslint-config-prettier": "^4.1.0",
"eslint-plugin-prettier": "^3.0.1",
"eslint-plugin-typescript": "^0.14.0",
"express": "^4.17.1",
"mocha": "^9.2.0",
"typescript": "^3.6.2",
"typescript-eslint-parser": "^22.0.0"
"typescript": "^3.6.2"
},

@@ -43,3 +37,7 @@ "dependencies": {

"lodash.unset": "4.5.2"
}
},
"lint-staged": {
"*.{ts,js}": "eslint --fix"
},
"gitHead": "688ef22f4d915e06612372d1308fde4b27a38090"
}

@@ -48,3 +48,3 @@ import { Db } from './index'

collectionName: this._collectionName,
stages: this._stages
stages: this._stages,
})

@@ -58,3 +58,3 @@

ok: false,
code: res.code
code: res.code,
}

@@ -67,3 +67,3 @@ }

requestId: res.requestId,
ok: true
ok: true,
}

@@ -80,3 +80,3 @@ return result

return {
[stageKey]: JSON.parse(stageValue)
[stageKey]: JSON.parse(stageValue),
}

@@ -97,3 +97,3 @@ })

stageKey: raw ? stage : `$${stage}`,
stageValue: transformParam
stageValue: transformParam,
})

@@ -125,3 +125,6 @@ return this

// 判断是否有 distanceMultiplier 参数
if (param.distanceMultiplier && typeof (param.distanceMultiplier) === 'number') {
if (
param.distanceMultiplier &&
typeof param.distanceMultiplier === 'number'
) {
param.distanceMultiplier = param.distanceMultiplier * EARTH_RADIUS

@@ -128,0 +131,0 @@ } else {

@@ -7,3 +7,2 @@ import { Db } from './index'

/**

@@ -50,4 +49,4 @@ * 集合模块,继承 Query 模块

*/
add(data: Object, options?: { multi: boolean }) {
let docRef = new DocumentReference(this._db, this._coll, undefined)
add(data: object, options?: { multi: boolean }) {
const docRef = new DocumentReference(this._db, this._coll, undefined)
return docRef.create(data, options)

@@ -63,4 +62,7 @@ }

*/
public async createIndex(keys: Record<string, number | string>, options?: any): Promise<CreateIndexRes> {
let docRef = new DocumentReference(this._db, this._coll, undefined)
public async createIndex(
keys: Record<string, number | string>,
options?: any
): Promise<CreateIndexRes> {
const docRef = new DocumentReference(this._db, this._coll, undefined)
return docRef.createIndex(keys, options)

@@ -72,4 +74,6 @@ }

*/
public async dropIndex(index: string | Record<string, number | string>): Promise<DropIndexRes> {
let docRef = new DocumentReference(this._db, this._coll, undefined)
public async dropIndex(
index: string | Record<string, number | string>
): Promise<DropIndexRes> {
const docRef = new DocumentReference(this._db, this._coll, undefined)
return docRef.dropIndex(index)

@@ -79,5 +83,5 @@ }

public async listIndexes(): Promise<ListIndexesRes> {
let docRef = new DocumentReference(this._db, this._coll, undefined)
const docRef = new DocumentReference(this._db, this._coll, undefined)
return docRef.listIndexes()
}
}

@@ -1,2 +0,9 @@

import { IGeoIntersectsOptions, IGeoNearOptions, IGeoWithinOptions, QueryCommand, QUERY_COMMANDS_LITERAL } from './commands/query'
/* eslint-disable prefer-rest-params */
import {
IGeoIntersectsOptions,
IGeoNearOptions,
IGeoWithinOptions,
QueryCommand,
QUERY_COMMANDS_LITERAL,
} from './commands/query'
import { LogicCommand, LOGIC_COMMANDS_LITERAL } from './commands/logic'

@@ -7,8 +14,5 @@ import { UpdateCommand, UPDATE_COMMANDS_LITERAL } from './commands/update'

export type IQueryCondition = Record<string, any> | LogicCommand
export const Command = {
eq(val: any) {

@@ -83,3 +87,5 @@ return new QueryCommand(QUERY_COMMANDS_LITERAL.EQ, [val])

and(...__expressions__: IQueryCondition[]) {
const expressions = isArray(arguments[0]) ? arguments[0] : Array.from(arguments)
const expressions = isArray(arguments[0])
? arguments[0]
: Array.from(arguments)
return new LogicCommand(LOGIC_COMMANDS_LITERAL.AND, expressions)

@@ -89,3 +95,5 @@ },

nor(...__expressions__: IQueryCondition[]) {
const expressions = isArray(arguments[0]) ? arguments[0] : Array.from(arguments)
const expressions = isArray(arguments[0])
? arguments[0]
: Array.from(arguments)
return new LogicCommand(LOGIC_COMMANDS_LITERAL.NOR, expressions)

@@ -95,3 +103,5 @@ },

or(...__expressions__: IQueryCondition[]) {
const expressions = isArray(arguments[0]) ? arguments[0] : Array.from(arguments)
const expressions = isArray(arguments[0])
? arguments[0]
: Array.from(arguments)
return new LogicCommand(LOGIC_COMMANDS_LITERAL.OR, expressions)

@@ -101,3 +111,5 @@ },

not(...__expressions__: IQueryCondition[]) {
const expressions = isArray(arguments[0]) ? arguments[0] : Array.from(arguments)
const expressions = isArray(arguments[0])
? arguments[0]
: Array.from(arguments)
return new LogicCommand(LOGIC_COMMANDS_LITERAL.NOT, expressions)

@@ -130,3 +142,3 @@ },

$sort: options.sort,
$slice: options.slice
$slice: options.slice,
}

@@ -185,3 +197,3 @@ } else if (isArray(args[0])) {

return {
$expr: values
$expr: values,
}

@@ -192,15 +204,19 @@ },

return {
$jsonSchema: schema
$jsonSchema: schema,
}
},
text(values: string | {
search: string
language?: string
caseSensitive?: boolean
diacriticSensitive: boolean
}) {
text(
values:
| string
| {
search: string
language?: string
caseSensitive?: boolean
diacriticSensitive: boolean
}
) {
if (isString(values)) {
return {
$search: values.search
$search: values.search,
}

@@ -212,3 +228,3 @@ } else {

$caseSensitive: values.caseSensitive,
$diacriticSensitive: values.diacriticSensitive
$diacriticSensitive: values.diacriticSensitive,
}

@@ -302,7 +318,9 @@ }

// 集合操作符(7个)
allElementsTrue: (param) => new AggregationOperator('allElementsTrue', param),
allElementsTrue: (param) =>
new AggregationOperator('allElementsTrue', param),
anyElementTrue: (param) => new AggregationOperator('anyElementTrue', param),
setDifference: (param) => new AggregationOperator('setDifference', param),
setEquals: (param) => new AggregationOperator('setEquals', param),
setIntersection: (param) => new AggregationOperator('setIntersection', param),
setIntersection: (param) =>
new AggregationOperator('setIntersection', param),
setIsSubset: (param) => new AggregationOperator('setIsSubset', param),

@@ -346,3 +364,3 @@ setUnion: (param) => new AggregationOperator('setUnion', param),

// 变量声明操作符
let: (param) => new AggregationOperator('let', param)
let: (param) => new AggregationOperator('let', param),
},

@@ -352,4 +370,4 @@

slice: (param) => new ProjectionOperator('slice', param),
elemMatch: (param) => new ProjectionOperator('elemMatch', param)
}
elemMatch: (param) => new ProjectionOperator('elemMatch', param),
},
}

@@ -370,2 +388,1 @@

export default Command

@@ -1,2 +0,7 @@

import { InternalSymbol, SYMBOL_UNSET_FIELD_NAME, SYMBOL_LOGIC_COMMAND } from '../helper/symbol'
/* eslint-disable prefer-rest-params */
import {
InternalSymbol,
SYMBOL_UNSET_FIELD_NAME,
SYMBOL_LOGIC_COMMAND,
} from '../helper/symbol'
import { isQueryCommand } from './query'

@@ -17,3 +22,2 @@

export class LogicCommand {
public fieldName: string | InternalSymbol

@@ -24,4 +28,7 @@ public operator: LOGIC_COMMANDS_LITERAL | string

constructor(operator: LOGIC_COMMANDS_LITERAL | string, operands: any, fieldName?: string | InternalSymbol) {
constructor(
operator: LOGIC_COMMANDS_LITERAL | string,
operands: any,
fieldName?: string | InternalSymbol
) {
Object.defineProperties(this, {

@@ -85,3 +92,3 @@ _internalType: {

_setFieldName(fieldName: string): LogicCommand {
const operands = this.operands.map(operand => {
const operands = this.operands.map((operand) => {
if (operand instanceof LogicCommand) {

@@ -103,5 +110,11 @@ return operand._setFieldName(fieldName)

and(...__expressions__: LogicCommand[]) {
const expressions: any[] = Array.isArray(arguments[0]) ? arguments[0] : Array.from(arguments)
const expressions: any[] = Array.isArray(arguments[0])
? arguments[0]
: Array.from(arguments)
expressions.unshift(this)
return new LogicCommand(LOGIC_COMMANDS_LITERAL.AND, expressions, this.fieldName)
return new LogicCommand(
LOGIC_COMMANDS_LITERAL.AND,
expressions,
this.fieldName
)
}

@@ -114,5 +127,11 @@

or(...__expressions__: LogicCommand[]) {
const expressions: any[] = Array.isArray(arguments[0]) ? arguments[0] : Array.from(arguments)
const expressions: any[] = Array.isArray(arguments[0])
? arguments[0]
: Array.from(arguments)
expressions.unshift(this)
return new LogicCommand(LOGIC_COMMANDS_LITERAL.OR, expressions, this.fieldName)
return new LogicCommand(
LOGIC_COMMANDS_LITERAL.OR,
expressions,
this.fieldName
)
}

@@ -129,13 +148,18 @@

*/
}
export function isLogicCommand(object: any): object is LogicCommand {
return object && (object instanceof LogicCommand) && (object._internalType === SYMBOL_LOGIC_COMMAND)
return (
object &&
object instanceof LogicCommand &&
object._internalType === SYMBOL_LOGIC_COMMAND
)
}
export function isKnownLogicCommand(object: any): object is LogicCommand {
return isLogicCommand && (object.operator.toUpperCase() in LOGIC_COMMANDS_LITERAL)
return (
isLogicCommand && object.operator.toUpperCase() in LOGIC_COMMANDS_LITERAL
)
}
export default LogicCommand
import { LogicCommand } from './logic'
import { InternalSymbol, SYMBOL_QUERY_COMMAND } from '../helper/symbol'
import { Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon } from '../geo/index'
import {
Point,
LineString,
Polygon,
MultiPoint,
MultiLineString,
MultiPolygon,
} from '../geo/index'
import { isNumber } from '../utils/type'

@@ -38,7 +45,7 @@

GEO_INTERSECTS = 'geoIntersects',
LIKE = 'like'
LIKE = 'like',
}
export class QueryCommand extends LogicCommand {
public operator: QUERY_COMMANDS_LITERAL;
public operator: QUERY_COMMANDS_LITERAL

@@ -60,7 +67,7 @@ constructor(

return {
['$' + this.operator]: this.operands
['$' + this.operator]: this.operands,
}
default:
return {
['$' + this.operator]: this.operands[0]
['$' + this.operator]: this.operands[0],
}

@@ -76,3 +83,7 @@ }

eq(val: any) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.EQ, [val], this.fieldName)
const command = new QueryCommand(
QUERY_COMMANDS_LITERAL.EQ,
[val],
this.fieldName
)
return this.and(command)

@@ -82,3 +93,7 @@ }

neq(val: any) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.NEQ, [val], this.fieldName)
const command = new QueryCommand(
QUERY_COMMANDS_LITERAL.NEQ,
[val],
this.fieldName
)
return this.and(command)

@@ -88,3 +103,7 @@ }

gt(val: any) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.GT, [val], this.fieldName)
const command = new QueryCommand(
QUERY_COMMANDS_LITERAL.GT,
[val],
this.fieldName
)
return this.and(command)

@@ -94,3 +113,7 @@ }

gte(val: any) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.GTE, [val], this.fieldName)
const command = new QueryCommand(
QUERY_COMMANDS_LITERAL.GTE,
[val],
this.fieldName
)
return this.and(command)

@@ -100,3 +123,7 @@ }

lt(val: any) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.LT, [val], this.fieldName)
const command = new QueryCommand(
QUERY_COMMANDS_LITERAL.LT,
[val],
this.fieldName
)
return this.and(command)

@@ -106,3 +133,7 @@ }

lte(val: any) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.LTE, [val], this.fieldName)
const command = new QueryCommand(
QUERY_COMMANDS_LITERAL.LTE,
[val],
this.fieldName
)
return this.and(command)

@@ -112,3 +143,7 @@ }

in(list: any[]) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.IN, list, this.fieldName)
const command = new QueryCommand(
QUERY_COMMANDS_LITERAL.IN,
list,
this.fieldName
)
return this.and(command)

@@ -118,3 +153,7 @@ }

nin(list: any[]) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.NIN, list, this.fieldName)
const command = new QueryCommand(
QUERY_COMMANDS_LITERAL.NIN,
list,
this.fieldName
)
return this.and(command)

@@ -125,3 +164,5 @@ }

if (!(val.geometry instanceof Point)) {
throw new TypeError(`"geometry" must be of type Point. Received type ${typeof val.geometry}`)
throw new TypeError(
`"geometry" must be of type Point. Received type ${typeof val.geometry}`
)
}

@@ -138,3 +179,7 @@ if (val.maxDistance !== undefined && !isNumber(val.maxDistance)) {

}
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.GEO_NEAR, [val], this.fieldName)
const command = new QueryCommand(
QUERY_COMMANDS_LITERAL.GEO_NEAR,
[val],
this.fieldName
)
return this.and(command)

@@ -144,3 +189,6 @@ }

geoWithin(val: IGeoWithinOptions) {
if (!(val.geometry instanceof MultiPolygon) && !(val.geometry instanceof Polygon)) {
if (
!(val.geometry instanceof MultiPolygon) &&
!(val.geometry instanceof Polygon)
) {
throw new TypeError(

@@ -150,3 +198,7 @@ `"geometry" must be of type Polygon or MultiPolygon. Received type ${typeof val.geometry}`

}
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.GEO_WITHIN, [val], this.fieldName)
const command = new QueryCommand(
QUERY_COMMANDS_LITERAL.GEO_WITHIN,
[val],
this.fieldName
)
return this.and(command)

@@ -168,3 +220,7 @@ }

}
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.GEO_INTERSECTS, [val], this.fieldName)
const command = new QueryCommand(
QUERY_COMMANDS_LITERAL.GEO_INTERSECTS,
[val],
this.fieldName
)
return this.and(command)

@@ -175,7 +231,14 @@ }

export function isQueryCommand(object: any): object is QueryCommand {
return object && object instanceof QueryCommand && object._internalType === SYMBOL_QUERY_COMMAND
return (
object &&
object instanceof QueryCommand &&
object._internalType === SYMBOL_QUERY_COMMAND
)
}
export function isKnownQueryCommand(object: any): object is QueryCommand {
return isQueryCommand(object) && object.operator.toUpperCase() in QUERY_COMMANDS_LITERAL
return (
isQueryCommand(object) &&
object.operator.toUpperCase() in QUERY_COMMANDS_LITERAL
)
}

@@ -190,13 +253,19 @@

export interface IGeoNearOptions {
geometry: Point;
maxDistance?: number;
minDistance?: number;
geometry: Point
maxDistance?: number
minDistance?: number
}
export interface IGeoWithinOptions {
geometry: Polygon | MultiPolygon;
geometry: Polygon | MultiPolygon
}
export interface IGeoIntersectsOptions {
geometry: Point | LineString | Polygon | MultiPoint | MultiLineString | MultiPolygon;
geometry:
| Point
| LineString
| Polygon
| MultiPoint
| MultiLineString
| MultiPolygon
}

@@ -1,2 +0,6 @@

import { InternalSymbol, SYMBOL_UNSET_FIELD_NAME, SYMBOL_UPDATE_COMMAND } from '../helper/symbol'
import {
InternalSymbol,
SYMBOL_UNSET_FIELD_NAME,
SYMBOL_UPDATE_COMMAND,
} from '../helper/symbol'

@@ -18,7 +22,6 @@ export enum UPDATE_COMMANDS_LITERAL {

MAX = 'max',
MIN = 'min'
MIN = 'min',
}
export class UpdateCommand {
public fieldName: string | InternalSymbol

@@ -29,4 +32,7 @@ public operator: UPDATE_COMMANDS_LITERAL

constructor(operator: UPDATE_COMMANDS_LITERAL, operands?: any, fieldName?: string | InternalSymbol) {
constructor(
operator: UPDATE_COMMANDS_LITERAL,
operands?: any,
fieldName?: string | InternalSymbol
) {
Object.defineProperties(this, {

@@ -51,9 +57,16 @@ _internalType: {

export function isUpdateCommand(object: any): object is UpdateCommand {
return object && (object instanceof UpdateCommand) && (object._internalType === SYMBOL_UPDATE_COMMAND)
return (
object &&
object instanceof UpdateCommand &&
object._internalType === SYMBOL_UPDATE_COMMAND
)
}
export function isKnownUpdateCommand(object: any): object is UpdateCommand {
return isUpdateCommand(object) && (object.operator.toUpperCase() in UPDATE_COMMANDS_LITERAL)
return (
isUpdateCommand(object) &&
object.operator.toUpperCase() in UPDATE_COMMANDS_LITERAL
)
}
export default UpdateCommand

@@ -17,3 +17,3 @@ /**

QueryParamTypeError = '查询参数必须为对象',
QueryParamValueError = '查询参数对象值不能均为undefined'
QueryParamValueError = '查询参数对象值不能均为undefined',
}

@@ -42,3 +42,3 @@

ObjectId: 'ObjectId',
Binary: 'Binary'
Binary: 'Binary',
}

@@ -74,3 +74,3 @@

gte = '>=',
eq = '=='
eq = '==',
}

@@ -87,3 +87,3 @@

[Operator.gt]: '$gt',
[Operator.gte]: '$gte'
[Operator.gte]: '$gte',
}

@@ -102,3 +102,3 @@

'$each',
'$position'
'$position',
]

@@ -114,4 +114,4 @@

createIndex = 'database.createIndex',
dropIndex = "database.dropIndex",
listIndexes = "database.listIndexes",
dropIndex = 'database.dropIndex',
listIndexes = 'database.listIndexes',
}

@@ -129,3 +129,3 @@

UpdateOperatorList,
ActionType
ActionType,
}

@@ -1,2 +0,1 @@

import { Db } from './index'

@@ -6,9 +5,16 @@ import { serialize } from './serializer/datatype'

import { ActionType } from './constant'
import { AddRes, CreateIndexRes, DropIndexRes, GetOneRes, ListIndexesRes, RemoveRes, UpdateRes } from './result-types'
import {
AddRes,
CreateIndexRes,
DropIndexRes,
GetOneRes,
ListIndexesRes,
RemoveRes,
UpdateRes,
} from './result-types'
import { ProjectionType } from './interface'
import { Query } from './query'
/**
* Db document
* Db document
*/

@@ -61,7 +67,6 @@ export class DocumentReference {

data: serialize(data),
multi: options?.multi ?? false
multi: options?.multi ?? false,
}
const res = await this._query
.send(ActionType.add, params)
const res = await this._query.send(ActionType.add, params)

@@ -75,3 +80,3 @@ if (res.error) {

insertedCount: undefined,
code: res.code
code: res.code,
}

@@ -84,3 +89,3 @@ }

requestId: res.requestId,
ok: true
ok: true,
}

@@ -96,3 +101,3 @@ }

*/
async set(data: Object): Promise<UpdateRes> {
async set(data: object): Promise<UpdateRes> {
if (!this.id) {

@@ -105,3 +110,3 @@ throw new Error('document id cannot be empty')

if (typeof objs === 'object') {
for (let key in objs) {
for (const key in objs) {
if (objs[key] instanceof UpdateCommand) {

@@ -135,3 +140,3 @@ hasOperator = true

*/
async update(data: Object): Promise<UpdateRes> {
async update(data: object): Promise<UpdateRes> {
// 把所有更新数据转为带操作符的

@@ -173,6 +178,10 @@ const merge = true

field(projection: string[] | ProjectionType): DocumentReference {
return new DocumentReference(this._db, this._coll, this.id, this._query.field(projection))
return new DocumentReference(
this._db,
this._coll,
this.id,
this._query.field(projection)
)
}
/**

@@ -184,3 +193,3 @@ * 创建索引

async createIndex(keys: object, options?: object): Promise<CreateIndexRes> {
if (typeof keys !== 'object' || Object.keys(keys)?.length === 0) {
if (typeof keys !== 'object' || Object.keys(keys)?.length === 0) {
throw new Error('keys cannot be empty object')

@@ -191,3 +200,3 @@ }

keys,
options
options,
}

@@ -200,4 +209,3 @@

const res = await this._query
.send(ActionType.createIndex, params)
const res = await this._query.send(ActionType.createIndex, params)

@@ -227,4 +235,3 @@ if (res.error) {

const res = await this._query
.send(ActionType.dropIndex, params)
const res = await this._query.send(ActionType.dropIndex, params)

@@ -254,4 +261,3 @@ if (res.error) {

const res = await this._query
.send(ActionType.listIndexes, params)
const res = await this._query.send(ActionType.listIndexes, params)

@@ -264,3 +270,3 @@ if (res.error) {

code: res.code,
list: res.data.list
list: res.data.list,
}

@@ -267,0 +273,0 @@ }

@@ -6,2 +6,2 @@ export * from './point'

export * from './multiLineString'
export * from './multiPolygon'
export * from './multiPolygon'
export interface ISerializedPoint {
type: string,
coordinates: [number, number]
type: string
coordinates: [number, number]
}
export interface ISerializedLineString {
type: string,
coordinates: [number, number][]
type: string
coordinates: [number, number][]
}
export interface ISerializedPolygon {
type: string,
coordinates: [number, number][][]
type: string
coordinates: [number, number][][]
}
export interface ISerializedMultiPoint {
type: string,
coordinates: [number, number][]
type: string
coordinates: [number, number][]
}
export interface ISerializedMultiLineString {
type: string,
coordinates: [number, number][][]
type: string
coordinates: [number, number][][]
}
export interface ISerializedMultiPolygon {
type: string,
coordinates: [number, number][][][]
}
type: string
coordinates: [number, number][][][]
}

@@ -12,66 +12,72 @@ import { SYMBOL_GEO_LINE_STRING } from '../helper/symbol'

export class LineString {
readonly points: Point[]
readonly points: Point[]
/**
* 初始化
*
* @param points - GeoPoint
*/
constructor(points: Point[]) {
if (!isArray(points)) {
throw new TypeError(`"points" must be of type Point[]. Received type ${typeof points}`)
/**
* 初始化
*
* @param points - GeoPoint
*/
constructor(points: Point[]) {
if (!isArray(points)) {
throw new TypeError(
`"points" must be of type Point[]. Received type ${typeof points}`
)
}
if (points.length < 2) {
throw new Error('"points" must contain 2 points at least')
}
points.forEach((point) => {
if (!(point instanceof Point)) {
throw new TypeError(
`"points" must be of type Point[]. Received type ${typeof point}[]`
)
}
if (points.length < 2) {
throw new Error('"points" must contain 2 points at least')
}
points.forEach(point => {
if (!(point instanceof Point)) {
throw new TypeError(`"points" must be of type Point[]. Received type ${typeof point}[]`)
}
})
})
this.points = points
this.points = points
}
parse(key) {
return {
[key]: {
type: 'LineString',
coordinates: this.points.map((point) => point.toJSON().coordinates),
},
}
}
parse(key) {
return {
[key]: {
type: 'LineString',
coordinates: this.points.map(point => point.toJSON().coordinates)
}
}
toJSON() {
return {
type: 'LineString',
coordinates: this.points.map((point) => point.toJSON().coordinates),
}
}
toJSON() {
return {
type: 'LineString',
coordinates: this.points.map(point => point.toJSON().coordinates)
}
static validate(lineString: ISerializedLineString) {
if (lineString.type !== 'LineString' || !isArray(lineString.coordinates)) {
return false
}
static validate(lineString: ISerializedLineString) {
if (lineString.type !== 'LineString' || !isArray(lineString.coordinates)) {
for (const point of lineString.coordinates) {
if (!isNumber(point[0]) || !isNumber(point[1])) {
return false
}
for (let point of lineString.coordinates) {
if (!isNumber(point[0]) || !isNumber(point[1])) {
return false
}
}
return true
}
return true
}
static isClosed(lineString: LineString) {
const firstPoint = lineString.points[0]
const lastPoint = lineString.points[lineString.points.length - 1]
static isClosed(lineString: LineString) {
const firstPoint = lineString.points[0]
const lastPoint = lineString.points[lineString.points.length - 1]
if (firstPoint.latitude === lastPoint.latitude && firstPoint.longitude === lastPoint.longitude) {
return true
}
if (
firstPoint.latitude === lastPoint.latitude &&
firstPoint.longitude === lastPoint.longitude
) {
return true
}
}
get _internalType() {
return SYMBOL_GEO_LINE_STRING
}
get _internalType() {
return SYMBOL_GEO_LINE_STRING
}
}

@@ -6,3 +6,2 @@ import { SYMBOL_GEO_MULTI_LINE_STRING } from '../helper/symbol'

/**

@@ -14,63 +13,69 @@ * 多个 LineString

export class MultiLineString {
readonly lines: LineString[]
readonly lines: LineString[]
/**
* 初始化
*
* @param lines - LineString
*/
constructor(lines: LineString[]) {
if (!isArray(lines)) {
throw new TypeError(`"lines" must be of type LineString[]. Received type ${typeof lines}`)
/**
* 初始化
*
* @param lines - LineString
*/
constructor(lines: LineString[]) {
if (!isArray(lines)) {
throw new TypeError(
`"lines" must be of type LineString[]. Received type ${typeof lines}`
)
}
if (lines.length === 0) {
throw new Error('Polygon must contain 1 linestring at least')
}
lines.forEach((line) => {
if (!(line instanceof LineString)) {
throw new TypeError(
`"lines" must be of type LineString[]. Received type ${typeof line}[]`
)
}
if (lines.length === 0) {
throw new Error('Polygon must contain 1 linestring at least')
}
lines.forEach(line => {
if (!(line instanceof LineString)) {
throw new TypeError(`"lines" must be of type LineString[]. Received type ${typeof line}[]`)
}
})
})
this.lines = lines
this.lines = lines
}
parse(key) {
return {
[key]: {
type: 'MultiLineString',
coordinates: this.lines.map((line) => {
return line.points.map((point) => [point.longitude, point.latitude])
}),
},
}
}
parse(key) {
return {
[key]: {
type: 'MultiLineString',
coordinates: this.lines.map(line => {
return line.points.map(point => [point.longitude, point.latitude])
})
}
}
toJSON() {
return {
type: 'MultiLineString',
coordinates: this.lines.map((line) => {
return line.points.map((point) => [point.longitude, point.latitude])
}),
}
}
toJSON() {
return {
type: 'MultiLineString',
coordinates: this.lines.map(line => {
return line.points.map(point => [point.longitude, point.latitude])
})
}
static validate(multiLineString: ISerializedMultiLineString) {
if (
multiLineString.type !== 'MultiLineString' ||
!isArray(multiLineString.coordinates)
) {
return false
}
static validate(multiLineString: ISerializedMultiLineString) {
if (multiLineString.type !== 'MultiLineString' || !isArray(multiLineString.coordinates)) {
return false
}
for (let line of multiLineString.coordinates) {
for (let point of line) {
if (!isNumber(point[0]) || !isNumber(point[1])) {
return false
}
for (const line of multiLineString.coordinates) {
for (const point of line) {
if (!isNumber(point[0]) || !isNumber(point[1])) {
return false
}
}
return true
}
return true
}
get _internalType() {
return SYMBOL_GEO_MULTI_LINE_STRING
}
get _internalType() {
return SYMBOL_GEO_MULTI_LINE_STRING
}
}

@@ -12,57 +12,60 @@ import { SYMBOL_GEO_MULTI_POINT } from '../helper/symbol'

export class MultiPoint {
readonly points: Point[]
readonly points: Point[]
/**
* 初始化
*
* @param points - GeoPoint
*/
constructor(points: Point[]) {
if (!isArray(points)) {
throw new TypeError(`"points" must be of type Point[]. Received type ${typeof points}`)
/**
* 初始化
*
* @param points - GeoPoint
*/
constructor(points: Point[]) {
if (!isArray(points)) {
throw new TypeError(
`"points" must be of type Point[]. Received type ${typeof points}`
)
}
if (points.length === 0) {
throw new Error('"points" must contain 1 point at least')
}
points.forEach((point) => {
if (!(point instanceof Point)) {
throw new TypeError(
`"points" must be of type Point[]. Received type ${typeof point}[]`
)
}
if (points.length === 0) {
throw new Error('"points" must contain 1 point at least')
}
points.forEach(point => {
if (!(point instanceof Point)) {
throw new TypeError(`"points" must be of type Point[]. Received type ${typeof point}[]`)
}
})
})
this.points = points
this.points = points
}
parse(key) {
return {
[key]: {
type: 'MultiPoint',
coordinates: this.points.map((point) => point.toJSON().coordinates),
},
}
}
parse(key) {
return {
[key]: {
type: 'MultiPoint',
coordinates: this.points.map(point => point.toJSON().coordinates)
}
}
toJSON() {
return {
type: 'MultiPoint',
coordinates: this.points.map((point) => point.toJSON().coordinates),
}
}
toJSON() {
return {
type: 'MultiPoint',
coordinates: this.points.map(point => point.toJSON().coordinates)
}
static validate(multiPoint: ISerializedMultiPoint) {
if (multiPoint.type !== 'MultiPoint' || !isArray(multiPoint.coordinates)) {
return false
}
static validate(multiPoint: ISerializedMultiPoint) {
if (multiPoint.type !== 'MultiPoint' || !isArray(multiPoint.coordinates)) {
for (const point of multiPoint.coordinates) {
if (!isNumber(point[0]) || !isNumber(point[1])) {
return false
}
for (let point of multiPoint.coordinates) {
if (!isNumber(point[0]) || !isNumber(point[1])) {
return false
}
}
return true
}
return true
}
get _internalType() {
return SYMBOL_GEO_MULTI_POINT
}
get _internalType() {
return SYMBOL_GEO_MULTI_POINT
}
}

@@ -6,3 +6,2 @@ import { SYMBOL_GEO_POLYGON } from '../helper/symbol'

/**

@@ -14,69 +13,75 @@ * 多个面

export class MultiPolygon {
readonly polygons: Polygon[]
readonly polygons: Polygon[]
/**
* 初始化
*
* @param polygons - Polygon[]
*/
constructor(polygons: Polygon[]) {
if (!isArray(polygons)) {
throw new TypeError(`"polygons" must be of type Polygon[]. Received type ${typeof polygons}`)
/**
* 初始化
*
* @param polygons - Polygon[]
*/
constructor(polygons: Polygon[]) {
if (!isArray(polygons)) {
throw new TypeError(
`"polygons" must be of type Polygon[]. Received type ${typeof polygons}`
)
}
if (polygons.length === 0) {
throw new Error('MultiPolygon must contain 1 polygon at least')
}
for (const polygon of polygons) {
if (!(polygon instanceof Polygon)) {
throw new TypeError(
`"polygon" must be of type Polygon[]. Received type ${typeof polygon}[]`
)
}
if (polygons.length === 0) {
throw new Error('MultiPolygon must contain 1 polygon at least')
}
for (let polygon of polygons) {
if (!(polygon instanceof Polygon)) {
throw new TypeError(`"polygon" must be of type Polygon[]. Received type ${typeof polygon}[]`)
}
}
this.polygons = polygons
}
parse(key) {
return {
[key]: {
type: 'MultiPolygon',
coordinates: this.polygons.map(polygon => {
return polygon.lines.map(line => {
return line.points.map(point => [point.longitude, point.latitude])
})
this.polygons = polygons
}
parse(key) {
return {
[key]: {
type: 'MultiPolygon',
coordinates: this.polygons.map((polygon) => {
return polygon.lines.map((line) => {
return line.points.map((point) => [point.longitude, point.latitude])
})
}
}
}),
},
}
}
toJSON() {
return {
type: 'MultiPolygon',
coordinates: this.polygons.map(polygon => {
return polygon.lines.map(line => {
return line.points.map(point => [point.longitude, point.latitude])
})
toJSON() {
return {
type: 'MultiPolygon',
coordinates: this.polygons.map((polygon) => {
return polygon.lines.map((line) => {
return line.points.map((point) => [point.longitude, point.latitude])
})
}
}),
}
}
static validate(multiPolygon: ISerializedMultiPolygon) {
if (multiPolygon.type !== 'MultiPolygon' || !isArray(multiPolygon.coordinates)) {
return false
}
for (let polygon of multiPolygon.coordinates) {
for (let line of polygon) {
for (let point of line) {
if (!isNumber(point[0]) || !isNumber(point[1])) {
return false
}
static validate(multiPolygon: ISerializedMultiPolygon) {
if (
multiPolygon.type !== 'MultiPolygon' ||
!isArray(multiPolygon.coordinates)
) {
return false
}
for (const polygon of multiPolygon.coordinates) {
for (const line of polygon) {
for (const point of line) {
if (!isNumber(point[0]) || !isNumber(point[1])) {
return false
}
}
}
return true
}
return true
}
get _internalType() {
return SYMBOL_GEO_POLYGON
}
get _internalType() {
return SYMBOL_GEO_POLYGON
}
}

@@ -16,3 +16,3 @@ import { Validate } from '../validate'

*/
readonly latitude: number;
readonly latitude: number

@@ -23,3 +23,3 @@ /**

*/
readonly longitude: number;
readonly longitude: number

@@ -44,4 +44,4 @@ /**

type: 'Point',
coordinates: [this.longitude, this.latitude]
}
coordinates: [this.longitude, this.latitude],
},
}

@@ -53,6 +53,3 @@ }

type: 'Point',
coordinates: [
this.longitude,
this.latitude,
],
coordinates: [this.longitude, this.latitude],
}

@@ -66,6 +63,8 @@ }

static validate(point: ISerializedPoint) {
return point.type === 'Point' &&
return (
point.type === 'Point' &&
isArray(point.coordinates) &&
Validate.isGeopoint('longitude', point.coordinates[0]) &&
Validate.isGeopoint('latitude', point.coordinates[1])
)
}

@@ -72,0 +71,0 @@

@@ -12,80 +12,87 @@ import { SYMBOL_GEO_MULTI_POLYGON } from '../helper/symbol'

export class Polygon {
readonly lines: LineString[]
readonly lines: LineString[]
/**
* 初始化
*
* @param lines - LineString
*/
constructor(lines: LineString[]) {
if (!isArray(lines)) {
throw new TypeError(`"lines" must be of type LineString[]. Received type ${typeof lines}`)
/**
* 初始化
*
* @param lines - LineString
*/
constructor(lines: LineString[]) {
if (!isArray(lines)) {
throw new TypeError(
`"lines" must be of type LineString[]. Received type ${typeof lines}`
)
}
if (lines.length === 0) {
throw new Error('Polygon must contain 1 linestring at least')
}
lines.forEach((line) => {
if (!(line instanceof LineString)) {
throw new TypeError(
`"lines" must be of type LineString[]. Received type ${typeof line}[]`
)
}
if (lines.length === 0) {
throw new Error('Polygon must contain 1 linestring at least')
if (!LineString.isClosed(line)) {
throw new Error(
`LineString ${line.points.map((p) =>
p.toReadableString()
)} is not a closed cycle`
)
}
lines.forEach(line => {
if (!(line instanceof LineString)) {
throw new TypeError(`"lines" must be of type LineString[]. Received type ${typeof line}[]`)
}
if (!LineString.isClosed(line)) {
throw new Error(`LineString ${line.points.map(p => p.toReadableString())} is not a closed cycle`)
}
})
})
this.lines = lines
this.lines = lines
}
parse(key) {
return {
[key]: {
type: 'Polygon',
coordinates: this.lines.map((line) => {
return line.points.map((point) => [point.longitude, point.latitude])
}),
},
}
}
parse(key) {
return {
[key]: {
type: 'Polygon',
coordinates: this.lines.map(line => {
return line.points.map(point => [point.longitude, point.latitude])
})
}
}
toJSON() {
return {
type: 'Polygon',
coordinates: this.lines.map((line) => {
return line.points.map((point) => [point.longitude, point.latitude])
}),
}
}
toJSON() {
return {
type: 'Polygon',
coordinates: this.lines.map(line => {
return line.points.map(point => [point.longitude, point.latitude])
})
}
static validate(polygon: ISerializedPolygon) {
if (polygon.type !== 'Polygon' || !isArray(polygon.coordinates)) {
return false
}
static validate(polygon: ISerializedPolygon) {
if (polygon.type !== 'Polygon' || !isArray(polygon.coordinates)) {
for (const line of polygon.coordinates) {
if (!this.isCloseLineString(line)) {
return false
}
for (let line of polygon.coordinates) {
if (!this.isCloseLineString(line)) {
for (const point of line) {
if (!isNumber(point[0]) || !isNumber(point[1])) {
return false
}
for (let point of line) {
if (!isNumber(point[0]) || !isNumber(point[1])) {
return false
}
}
}
return true
}
return true
}
static isCloseLineString(lineString) {
const firstPoint = lineString[0]
const lastPoint = lineString[lineString.length - 1]
static isCloseLineString(lineString) {
const firstPoint = lineString[0]
const lastPoint = lineString[lineString.length - 1]
if (firstPoint[0] !== lastPoint[0] || firstPoint[1] !== lastPoint[1]) {
return false
}
return true
if (firstPoint[0] !== lastPoint[0] || firstPoint[1] !== lastPoint[1]) {
return false
}
get _internalType() {
return SYMBOL_GEO_MULTI_POLYGON
}
return true
}
get _internalType() {
return SYMBOL_GEO_MULTI_POLYGON
}
}

@@ -11,7 +11,15 @@ import InternalSymbol from '../utils/symbol'

export const SYMBOL_GEO_POINT = InternalSymbol.for('GEO_POINT')
export const SYMBOL_GEO_LINE_STRING = InternalSymbol.for('SYMBOL_GEO_LINE_STRING')
export const SYMBOL_GEO_LINE_STRING = InternalSymbol.for(
'SYMBOL_GEO_LINE_STRING'
)
export const SYMBOL_GEO_POLYGON = InternalSymbol.for('SYMBOL_GEO_POLYGON')
export const SYMBOL_GEO_MULTI_POINT = InternalSymbol.for('SYMBOL_GEO_MULTI_POINT')
export const SYMBOL_GEO_MULTI_LINE_STRING = InternalSymbol.for('SYMBOL_GEO_MULTI_LINE_STRING')
export const SYMBOL_GEO_MULTI_POLYGON = InternalSymbol.for('SYMBOL_GEO_MULTI_POLYGON')
export const SYMBOL_GEO_MULTI_POINT = InternalSymbol.for(
'SYMBOL_GEO_MULTI_POINT'
)
export const SYMBOL_GEO_MULTI_LINE_STRING = InternalSymbol.for(
'SYMBOL_GEO_MULTI_LINE_STRING'
)
export const SYMBOL_GEO_MULTI_POLYGON = InternalSymbol.for(
'SYMBOL_GEO_MULTI_POLYGON'
)

@@ -18,0 +26,0 @@ export const SYMBOL_SERVER_DATE = InternalSymbol.for('SERVER_DATE')

@@ -11,3 +11,3 @@ import * as Geo from './geo/index'

* 地理位置类型
*/
*/
interface GeoType {

@@ -93,3 +93,3 @@ Point: typeof Geo.Point

* Generate a hex string id for document
* @returns
* @returns
*/

@@ -103,4 +103,4 @@ generateId(): string {

* Wrapper for ObjectId() of mongodb
* @param params
* @returns
* @param params
* @returns
*/

@@ -107,0 +107,0 @@ ObjectId(id?: string | number | ObjectId) {

@@ -1,2 +0,2 @@

import { ActionType, OrderByDirection } from "./constant"
import { ActionType, OrderByDirection } from './constant'

@@ -25,3 +25,3 @@ export interface ResponseStruct {

export interface AggregateStage {
stageKey: string,
stageKey: string
stageValue: any

@@ -31,3 +31,2 @@ }

export interface QueryParam {
collectionName: string

@@ -38,3 +37,3 @@

*/
query?: Object
query?: object
order?: QueryOrder[]

@@ -58,2 +57,2 @@ offset?: number

stages?: AggregateStage[]
}
}

@@ -8,9 +8,18 @@ import { ActionType, OrderByDirection } from './constant'

import { ErrorCode } from './constant'
import { GetOneRes, GetRes, CountRes, UpdateRes, RemoveRes} from './result-types'
import { ProjectionType, QueryOrder, RequestInterface, QueryParam } from './interface'
import {
GetOneRes,
GetRes,
CountRes,
UpdateRes,
RemoveRes,
} from './result-types'
import {
ProjectionType,
QueryOrder,
RequestInterface,
QueryParam,
} from './interface'
import { Util } from './util'
import { serialize } from './serializer/datatype'
interface QueryOption {

@@ -38,3 +47,2 @@ /**

interface WithParam {

@@ -54,3 +62,3 @@ /**

*/
foreignField: string,
foreignField: string

@@ -60,3 +68,3 @@ /**

*/
as?: string,
as?: string

@@ -66,6 +74,5 @@ /**

*/
one?: boolean,
one?: boolean
}
/**

@@ -88,3 +95,3 @@ * Db query

*/
private _fieldFilters: Object
private _fieldFilters: object

@@ -112,3 +119,3 @@ /**

/**
* @param db - db reference
* @param db - db reference
* @param coll - collection name

@@ -122,3 +129,3 @@ * @param fieldFilters - query condition

coll: string,
fieldFilters?: Object,
fieldFilters?: object,
fieldOrders?: QueryOrder[],

@@ -150,3 +157,3 @@ queryOptions?: QueryOption,

const checkFlag = keys.some(item => {
const checkFlag = keys.some((item) => {
return query[item] !== undefined

@@ -182,3 +189,3 @@ })

field: fieldPath,
direction: directionStr
direction: directionStr,
}

@@ -208,7 +215,14 @@ const combinedOrders = this._fieldOrders.concat(newOrder)

as: param.as ?? param.query._coll,
one: param.one ?? false
one: param.one ?? false,
}
const combinedWiths = this._withs.concat(newWith)
return new Query(this._db, this._coll, this._fieldFilters, this._fieldOrders, this._queryOptions, combinedWiths)
return new Query(
this._db,
this._coll,
this._fieldFilters,
this._fieldOrders,
this._queryOptions,
combinedWiths
)
}

@@ -227,7 +241,14 @@

as: param.as ?? param.query._coll,
one: true
one: true,
}
const combinedWiths = this._withs.concat(newWith)
return new Query(this._db, this._coll, this._fieldFilters, this._fieldOrders, this._queryOptions, combinedWiths)
return new Query(
this._db,
this._coll,
this._fieldFilters,
this._fieldOrders,
this._queryOptions,
combinedWiths
)
}

@@ -243,4 +264,4 @@

if (projection instanceof Array) {
let result = {} as ProjectionType
for (let k of projection) {
const result = {} as ProjectionType
for (const k of projection) {
result[k] = 1

@@ -250,3 +271,3 @@ }

} else {
for (let k in projection) {
for (const k in projection) {
if (projection[k]) {

@@ -265,3 +286,10 @@ if (typeof projection[k] !== 'object') {

return new Query(this._db, this._coll, this._fieldFilters, this._fieldOrders, option, this._withs)
return new Query(
this._db,
this._coll,
this._fieldFilters,
this._fieldOrders,
option,
this._withs
)
}

@@ -277,6 +305,13 @@

let option = { ...this._queryOptions }
const option = { ...this._queryOptions }
option.limit = limit
return new Query(this._db, this._coll, this._fieldFilters, this._fieldOrders, option, this._withs)
return new Query(
this._db,
this._coll,
this._fieldFilters,
this._fieldOrders,
option,
this._withs
)
}

@@ -292,6 +327,13 @@

let option = { ...this._queryOptions }
const option = { ...this._queryOptions }
option.offset = offset
return new Query(this._db, this._coll, this._fieldFilters, this._fieldOrders, option, this._withs)
return new Query(
this._db,
this._coll,
this._fieldFilters,
this._fieldOrders,
option,
this._withs
)
}

@@ -303,9 +345,7 @@

*/
public page(options: { current: number, size: number }) {
public page(options: { current: number; size: number }) {
const current = options?.current || 1
const size = options?.size || 10
const query = this
.skip((current - 1) * size)
.limit(size)
const query = this.skip((current - 1) * size).limit(size)

@@ -322,3 +362,10 @@ query._queryOptions.count = true

public clone(): Query {
return new Query(this._db, this._coll, this._fieldFilters, this._fieldOrders, this._queryOptions, this._withs)
return new Query(
this._db,
this._coll,
this._fieldFilters,
this._fieldOrders,
this._queryOptions,
this._withs
)
}

@@ -342,4 +389,4 @@

* 发起请求获取一个文档
* @param options
* @returns
* @param options
* @returns
*/

@@ -356,3 +403,3 @@ public async getOne<T = any>(): Promise<GetOneRes<T>> {

data: null,
requestId: res.requestId
requestId: res.requestId,
}

@@ -364,3 +411,3 @@ }

data: res.data[0],
requestId: res.requestId
requestId: res.requestId,
}

@@ -372,5 +419,5 @@ }

* 发起请求获取文档列表,当使用 with 条件时使用
*
* @deprecated
*
*
* @deprecated
*
* 1. 调用 get() 执行主查询

@@ -381,3 +428,5 @@ * 2. 结合主查询的结果,使用 in 执行子表查询

*/
public async merge<T = any>(options?: { intersection?: boolean }): Promise<GetRes<T>> {
public async merge<T = any>(options?: {
intersection?: boolean
}): Promise<GetRes<T>> {
const res = await this.internalMerge(options)

@@ -400,3 +449,3 @@ return res

total: undefined,
code: res.code
code: res.code,
}

@@ -408,3 +457,3 @@ }

total: res.data.total,
ok: true
ok: true,
}

@@ -418,4 +467,6 @@ }

*/
public async update(data: Object, options?: { multi?: boolean, merge?: boolean, upsert?: boolean }): Promise<UpdateRes> {
public async update(
data: object,
options?: { multi?: boolean; merge?: boolean; upsert?: boolean }
): Promise<UpdateRes> {
if (!data || typeof data !== 'object' || 0 === Object.keys(data)?.length) {

@@ -448,3 +499,3 @@ throw new Error('data cannot be empty object')

matched: undefined,
upsertId: undefined
upsertId: undefined,
}

@@ -458,3 +509,3 @@ }

upsertId: res.data.upsert_id,
ok: true
ok: true,
}

@@ -468,3 +519,5 @@ }

if (Object.keys(this._queryOptions).length > 0) {
console.warn('`offset`, `limit` and `projection` are not supported in remove() operation')
console.warn(
'`offset`, `limit` and `projection` are not supported in remove() operation'
)
}

@@ -486,3 +539,3 @@

deleted: undefined,
code: res.code
code: res.code,
}

@@ -494,3 +547,3 @@ }

deleted: res.data.deleted,
ok: true
ok: true,
}

@@ -501,3 +554,3 @@ }

* Build query param
* @returns
* @returns
*/

@@ -518,3 +571,4 @@ protected buildQueryParam() {

if (this._queryOptions.limit) {
param.limit = this._queryOptions.limit < 1000 ? this._queryOptions.limit : 1000
param.limit =
this._queryOptions.limit < 1000 ? this._queryOptions.limit : 1000
} else {

@@ -534,4 +588,4 @@ param.limit = 100

/**
* 发起请求获取文档列表
*/
* 发起请求获取文档列表
*/
protected async internalGet<T = any>(): Promise<GetRes<T>> {

@@ -546,3 +600,3 @@ const param = this.buildQueryParam()

ok: false,
code: res.code
code: res.code,
}

@@ -555,3 +609,3 @@ }

requestId: res.requestId,
ok: true
ok: true,
}

@@ -566,3 +620,3 @@ if (res.total) result.total = res.data?.total

* 发起请求获取文档列表,当使用 with 条件时使用
*
*
* 1. 调用 internalGet() 执行主查询

@@ -573,5 +627,6 @@ * 2. 结合主查询的结果,使用 in 执行子表查询

*/
protected async internalMerge<T = any>(options?: { intersection?: boolean }): Promise<GetRes<T>> {
options = options ?? {} as any
protected async internalMerge<T = any>(options?: {
intersection?: boolean
}): Promise<GetRes<T>> {
options = options ?? ({} as any)
const intersection = options?.intersection ?? false

@@ -586,8 +641,8 @@

// 针对每一个 WithParam 做合并处理
for (let _with of this._withs) {
for (const _with of this._withs) {
const { query, localField, foreignField, as, one } = _with
const localValues = res.data.map(localData => localData[localField])
const localValues = res.data.map((localData) => localData[localField])
// 处理子查询
let q = query.clone()
const q = query.clone()

@@ -597,8 +652,8 @@ if (!q._fieldFilters) {

}
q._fieldFilters[foreignField] = { '$in': localValues }
q._fieldFilters[foreignField] = { $in: localValues }
// 执行子查询
let r_sub: (GetRes<T>)
let r_sub: GetRes<T>
if (q._withs.length) {
r_sub = await q.merge() // 如果子查询也使用了 with/withOne,则使用 merge() 查询
r_sub = await q.merge() // 如果子查询也使用了 with/withOne,则使用 merge() 查询
} else {

@@ -612,3 +667,2 @@ r_sub = await q.get()

// 按照 localField -> foreignField 的连接关系将子查询结果聚合:

@@ -618,4 +672,4 @@

const _map = {}
for (let sub of r_sub.data) {
const key = sub[foreignField] // 将子表结果的连接键的值做为映射表的 key
for (const sub of r_sub.data) {
const key = sub[foreignField] // 将子表结果的连接键的值做为映射表的 key
if (one) {

@@ -625,3 +679,3 @@ _map[key] = sub

_map[key] = _map[key] || []
_map[key].push(sub) // 将子表结果放入映射表
_map[key].push(sub) // 将子表结果放入映射表
}

@@ -632,3 +686,3 @@ }

const results = []
for (let m of res.data) {
for (const m of res.data) {
// 此处主表结果中的 [value of `localField`] 与 上面子表结果中的 [value of `foreignField`] 应该是一致的

@@ -653,5 +707,5 @@ const key = m[localField]

* Send query request
* @param action
* @param param
* @returns
* @param action
* @param param
* @returns
*/

@@ -658,0 +712,0 @@ public async send(action: ActionType, param: QueryParam) {

@@ -9,3 +9,3 @@ import { SYMBOL_REGEXP } from '../helper/symbol'

$options: string
constructor({ regexp, options }: { regexp: string, options: string }) {
constructor({ regexp, options }: { regexp: string; options: string }) {
if (!regexp) {

@@ -21,3 +21,3 @@ throw new TypeError('regexp must be a string')

$regex: this.$regex,
$options: this.$options
$options: this.$options,
}

@@ -33,7 +33,7 @@ }

* @deprecated This method was deprecated, use js native `RegExp` instead
* @param param
* @returns
* @param param
* @returns
*/
export function RegExpConstructor(param: { regexp: string, options: string }) {
export function RegExpConstructor(param: { regexp: string; options: string }) {
return new RegExp(param)
}

@@ -1,2 +0,1 @@

interface BaseResult {

@@ -17,3 +16,3 @@ requestId?: string

export interface GetOneRes<T> extends BaseResult {
data: T
data: T | null
}

@@ -40,12 +39,12 @@

export interface CreateIndexRes extends BaseResult{
indexName: string
export interface CreateIndexRes extends BaseResult {
indexName: string
}
export interface DropIndexRes extends BaseResult{
result: any
export interface DropIndexRes extends BaseResult {
result: any
}
export interface ListIndexesRes extends BaseResult{
list: object[]
}
export interface ListIndexesRes extends BaseResult {
list: object[]
}

@@ -1,3 +0,15 @@

import { getType, isObject, isArray, isDate, isRegExp, isInternalObject, isObjectId, isBinary } from '../utils/type'
import { serialize as serializeInternalDataType, deserialize as deserializeInternalDataType } from './datatype'
import {
getType,
isObject,
isArray,
isDate,
isRegExp,
isInternalObject,
isObjectId,
isBinary,
} from '../utils/type'
import {
serialize as serializeInternalDataType,
deserialize as deserializeInternalDataType,
} from './datatype'
import { LogicCommand } from '../commands/logic'

@@ -15,5 +27,4 @@

parents: string[],
visited: object[],
visited: object[]
): Record<string, any> {
const cloned = { ...query }

@@ -29,3 +40,2 @@

if (isObject(value) && !shouldPreserverObject(value)) {
if (visited.indexOf(value) > -1) {

@@ -35,13 +45,12 @@ throw new Error('Cannot convert circular structure to JSON')

const newParents = [
...parents,
key,
]
const newParents = [...parents, key]
const newVisited = [
...visited,
const newVisited = [...visited, value]
const flattenedChild = flatten(
value,
]
const flattenedChild = flatten(value, shouldPreserverObject, newParents, newVisited)
shouldPreserverObject,
newParents,
newVisited
)
cloned[key] = flattenedChild

@@ -62,5 +71,3 @@

}
}
}

@@ -71,3 +78,5 @@

export function flattenQueryObject(query: Record<string, any>): Record<string, any> {
export function flattenQueryObject(
query: Record<string, any>
): Record<string, any> {
return flatten(query, isConversionRequired, [], [query])

@@ -80,3 +89,7 @@ }

export function mergeConditionAfterEncode(query: Record<string, any>, condition: Record<string, any>, key: string): void {
export function mergeConditionAfterEncode(
query: Record<string, any>,
condition: Record<string, any>,
key: string
): void {
if (!condition[key]) {

@@ -94,7 +107,18 @@ delete query[key]

} else {
console.warn(`unmergable condition, query is object but condition is ${getType(condition)}, can only overwrite`, condition, key)
console.warn(
`unmergable condition, query is object but condition is ${getType(
condition
)}, can only overwrite`,
condition,
key
)
query[conditionKey] = condition[conditionKey]
}
} else {
console.warn(`to-merge query is of type ${getType(query)}, can only overwrite`, query, condition, key)
console.warn(
`to-merge query is of type ${getType(query)}, can only overwrite`,
query,
condition,
key
)
query[conditionKey] = condition[conditionKey]

@@ -111,9 +135,15 @@ }

* InternalObject can be: `LogicCommand` | `QueryCommand` | `UpdateCommand`
*
*
* @tip this method also used is `flatten()` function, `flatten` will reserved the required object
* @param val
* @returns
* @param val
* @returns
*/
export function isConversionRequired(val: any): boolean {
return isInternalObject(val) || isDate(val) || isRegExp(val) || isObjectId(val) || isBinary(val)
return (
isInternalObject(val) ||
isDate(val) ||
isRegExp(val) ||
isObjectId(val) ||
isBinary(val)
)
}

@@ -120,0 +150,0 @@

// transpile internal data type
import { SYMBOL_GEO_POINT, SYMBOL_SERVER_DATE, SYMBOL_REGEXP } from '../helper/symbol'
import { getType, isObject, isArray, isDate, isNumber, isInternalObject, isRegExp, isObjectId, isBinary } from '../utils/type'
import {
SYMBOL_GEO_POINT,
SYMBOL_SERVER_DATE,
SYMBOL_REGEXP,
} from '../helper/symbol'
import {
getType,
isObject,
isArray,
isDate,
isNumber,
isInternalObject,
isRegExp,
isObjectId,
isBinary,
} from '../utils/type'
import { Point } from '../geo/index'

@@ -20,6 +34,3 @@ import { ServerDate } from '../serverDate/index'

function serializeHelper(
val: any,
visited: object[]
): Record<string, any> {
function serializeHelper(val: any, visited: object[]): Record<string, any> {
if (isInternalObject(val)) {

@@ -43,3 +54,3 @@ switch (val._internalType) {

} else if (isArray(val)) {
return val.map(item => {
return val.map((item) => {
if (visited.indexOf(item) > -1) {

@@ -49,6 +60,3 @@ throw new Error('Cannot convert circular structure to JSON')

return serializeHelper(item, [
...visited,
item,
])
return serializeHelper(item, [...visited, item])
})

@@ -62,6 +70,3 @@ } else if (isObject(val)) {

ret[key] = serializeHelper(ret[key], [
...visited,
ret[key],
])
ret[key] = serializeHelper(ret[key], [...visited, ret[key]])
}

@@ -95,3 +100,7 @@ return ret

// GeoPoint
if (isArray(ret.coordinates) && isNumber(ret.coordinates[0]) && isNumber(ret.coordinates[1])) {
if (
isArray(ret.coordinates) &&
isNumber(ret.coordinates[0]) &&
isNumber(ret.coordinates[1])
) {
return new Point(ret.coordinates[0], ret.coordinates[1])

@@ -98,0 +107,0 @@ }

@@ -5,3 +5,3 @@ import {

QUERY_COMMANDS_LITERAL,
QueryCommand
QueryCommand,
} from '../commands/query'

@@ -11,3 +11,3 @@ import {

LOGIC_COMMANDS_LITERAL,
LogicCommand
LogicCommand,
} from '../commands/logic'

@@ -20,3 +20,3 @@ import { SYMBOL_UNSET_FIELD_NAME } from '../helper/symbol'

isConversionRequired,
encodeInternalDataType
encodeInternalDataType,
} from './common'

@@ -26,3 +26,3 @@ import {

IGeoWithinOptions,
IGeoIntersectsOptions
IGeoIntersectsOptions,
} from '../commands/query'

@@ -33,3 +33,3 @@

export class QuerySerializer {
constructor() { }
constructor() {}

@@ -70,3 +70,3 @@ static encode(

$regex: query.source,
$options: query.flags
$options: query.flags,
}

@@ -81,7 +81,7 @@ }

const $op = operatorToString(query.operator)
const subqueries = query.operands.map(oprand =>
const subqueries = query.operands.map((oprand) =>
this.encodeQuery(oprand, query.fieldName)
)
return {
[$op]: subqueries
[$op]: subqueries,
}

@@ -96,13 +96,12 @@ }

[query.fieldName as string]: {
[$op]: this.encodeRegExp(operatorExpression)
}
[$op]: this.encodeRegExp(operatorExpression),
},
}
} else {
const subqueries = this.encodeQuery(operatorExpression)[
query.fieldName as string
]
const subqueries =
this.encodeQuery(operatorExpression)[query.fieldName as string]
return {
[query.fieldName as string]: {
[$op]: subqueries
}
[$op]: subqueries,
},
}

@@ -116,3 +115,3 @@ }

return {
[$op]: subquery
[$op]: subquery,
}

@@ -122,3 +121,3 @@ } else {

return {
[$op]: subqueries
[$op]: subqueries,
}

@@ -161,4 +160,4 @@ }

[query.fieldName as string]: {
[$op]: encodeInternalDataType(query.operands[0])
}
[$op]: encodeInternalDataType(query.operands[0]),
},
}

@@ -171,4 +170,4 @@ }

[query.fieldName as string]: {
[$op]: encodeInternalDataType(query.operands)
}
[$op]: encodeInternalDataType(query.operands),
},
}

@@ -183,5 +182,5 @@ }

$maxDistance: options.maxDistance,
$minDistance: options.minDistance
}
}
$minDistance: options.minDistance,
},
},
}

@@ -194,5 +193,5 @@ }

$geoWithin: {
$geometry: options.geometry.toJSON()
}
}
$geometry: options.geometry.toJSON(),
},
},
}

@@ -205,5 +204,5 @@ }

$geoIntersects: {
$geometry: options.geometry.toJSON()
}
}
$geometry: options.geometry.toJSON(),
},
},
}

@@ -214,4 +213,4 @@ }

[query.fieldName as string]: {
[$op]: encodeInternalDataType(query.operands[0])
}
[$op]: encodeInternalDataType(query.operands[0]),
},
}

@@ -218,0 +217,0 @@ }

import {
UpdateCommand,
isUpdateCommand,
UPDATE_COMMANDS_LITERAL
UPDATE_COMMANDS_LITERAL,
} from '../commands/update'

@@ -13,3 +13,3 @@ import { LogicCommand } from '../commands/logic'

encodeInternalDataType,
mergeConditionAfterEncode
mergeConditionAfterEncode,
} from './common'

@@ -28,3 +28,3 @@ export type IQueryCondition = Record<string, any> | LogicCommand

export class UpdateSerializer {
private constructor() { }
private constructor() {}

@@ -76,4 +76,4 @@ static encode(query: IQueryCondition | UpdateCommand): IUpdateCondition {

[$op]: {
[query.fieldName as string]: ''
}
[query.fieldName as string]: '',
},
}

@@ -84,4 +84,4 @@ }

[$op]: {
[query.fieldName as string]: query.operands[0]
}
[query.fieldName as string]: query.operands[0],
},
}

@@ -100,3 +100,3 @@ }

modifiers = {
$each: query.operands.map(encodeInternalDataType)
$each: query.operands.map(encodeInternalDataType),
}

@@ -109,4 +109,4 @@ } else {

[$op]: {
[query.fieldName as string]: modifiers
}
[query.fieldName as string]: modifiers,
},
}

@@ -117,3 +117,3 @@ }

$each: query.operands.map(encodeInternalDataType),
$position: 0
$position: 0,
}

@@ -123,4 +123,4 @@

[$op]: {
[query.fieldName as string]: modifiers
}
[query.fieldName as string]: modifiers,
},
}

@@ -131,4 +131,4 @@ }

[$op]: {
[query.fieldName as string]: 1
}
[query.fieldName as string]: 1,
},
}

@@ -139,4 +139,4 @@ }

[$op]: {
[query.fieldName as string]: -1
}
[query.fieldName as string]: -1,
},
}

@@ -147,4 +147,4 @@ }

[$op]: {
[query.fieldName as string]: encodeInternalDataType(query.operands)
}
[query.fieldName as string]: encodeInternalDataType(query.operands),
},
}

@@ -151,0 +151,0 @@ }

@@ -17,4 +17,4 @@ import { SYMBOL_SERVER_DATE } from '../helper/symbol'

$date: {
offset: this.offset
}
offset: this.offset,
},
}

@@ -26,7 +26,7 @@ }

* @deprecated This method is deprecated, not implemented in server side
* @param opt
* @returns
* @param opt
* @returns
*/
export function ServerDateConstructor(opt?: { offset: number }) {
return new ServerDate(opt)
}
}
import { Binary, EJSON, ObjectId } from 'bson'
import { FieldType } from './constant'
import { Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon } from './geo/index'
import {
Point,
LineString,
Polygon,
MultiPoint,
MultiLineString,
MultiPolygon,
} from './geo/index'
import { ServerDate } from './serverDate/index'

@@ -21,3 +28,3 @@

public static formatResDocumentData = (documents: DocumentModel[]) => {
return documents.map(document => {
return documents.map((document) => {
return Util.formatField(document)

@@ -35,3 +42,3 @@ })

*/
public static formatField = document => {
public static formatField = (document) => {
const keys = Object.keys(document)

@@ -45,3 +52,3 @@ let protoField = {}

keys.forEach(key => {
keys.forEach((key) => {
const item = document[key]

@@ -55,3 +62,5 @@ const type = Util.whichType(item)

case FieldType.GeoLineString:
realValue = new LineString(item.coordinates.map(point => new Point(point[0], point[1])))
realValue = new LineString(
item.coordinates.map((point) => new Point(point[0], point[1]))
)
break

@@ -61,3 +70,4 @@ case FieldType.GeoPolygon:

item.coordinates.map(
line => new LineString(line.map(([lng, lat]) => new Point(lng, lat)))
(line) =>
new LineString(line.map(([lng, lat]) => new Point(lng, lat)))
)

@@ -67,3 +77,5 @@ )

case FieldType.GeoMultiPoint:
realValue = new MultiPoint(item.coordinates.map(point => new Point(point[0], point[1])))
realValue = new MultiPoint(
item.coordinates.map((point) => new Point(point[0], point[1]))
)
break

@@ -73,3 +85,4 @@ case FieldType.GeoMultiLineString:

item.coordinates.map(
line => new LineString(line.map(([lng, lat]) => new Point(lng, lat)))
(line) =>
new LineString(line.map(([lng, lat]) => new Point(lng, lat)))
)

@@ -81,5 +94,10 @@ )

item.coordinates.map(
polygon =>
(polygon) =>
new Polygon(
polygon.map(line => new LineString(line.map(([lng, lat]) => new Point(lng, lat))))
polygon.map(
(line) =>
new LineString(
line.map(([lng, lat]) => new Point(lng, lat))
)
)
)

@@ -123,3 +141,3 @@ )

*/
public static whichType = (obj: any): String => {
public static whichType = (obj: any): string => {
let type = Object.prototype.toString.call(obj).slice(8, -1)

@@ -138,5 +156,3 @@

return FieldType.Command;
} */ else if (
obj instanceof ServerDate
) {
} */ else if (obj instanceof ServerDate) {
return FieldType.ServerDate

@@ -143,0 +159,0 @@ } else if (obj instanceof ObjectId) {

@@ -1,6 +0,5 @@

const _symbols: { target: any, instance: InternalSymbol }[] = []
const _symbols: { target: any; instance: InternalSymbol }[] = []
const __internalMark__ = {}
class HiddenSymbol {
constructor(target: any) {

@@ -19,6 +18,7 @@ Object.defineProperties(this, {

export class InternalSymbol extends HiddenSymbol {
constructor(target: any, __mark__: any) {
if (__mark__ !== __internalMark__) {
throw new TypeError('InternalSymbol cannot be constructed with new operator')
throw new TypeError(
'InternalSymbol cannot be constructed with new operator'
)
}

@@ -30,3 +30,2 @@

static for(target: any) {
for (let i = 0, len = _symbols.length; i < len; i++) {

@@ -50,2 +49,1 @@ if (_symbols[i].target === target) {

export default InternalSymbol
import { Binary, ObjectId } from 'bson'
import { InternalSymbol } from './symbol'
export const getType = (x: any): string => Object.prototype.toString.call(x).slice(8, -1).toLowerCase()
export const getType = (x: any): string =>
Object.prototype.toString.call(x).slice(8, -1).toLowerCase()
export const isObject = <T extends object>(x: any): x is T => getType(x) === 'object'
export const isObject = <T extends object>(x: any): x is T =>
getType(x) === 'object'

@@ -12,8 +14,12 @@ export const isString = (x: any): x is string => getType(x) === 'string'

export const isPromise = <T extends Promise<any> = Promise<any>>(x: any): x is T => getType(x) === 'promise'
export const isPromise = <T extends Promise<any> = Promise<any>>(
x: any
): x is T => getType(x) === 'promise'
type AnyFn = (...args: any[]) => any
export const isFunction = <T extends AnyFn = AnyFn>(x: any): x is T => typeof x === 'function'
export const isFunction = <T extends AnyFn = AnyFn>(x: any): x is T =>
typeof x === 'function'
export const isArray = <T extends any[] = any[]>(x: any): x is T => Array.isArray(x)
export const isArray = <T extends any[] = any[]>(x: any): x is T =>
Array.isArray(x)

@@ -26,6 +32,7 @@ export const isDate = (x: any): x is Date => getType(x) === 'date'

* Internal Object can be: `LogicCommand` | `QueryCommand` | `UpdateCommand`
* @param x
* @returns
* @param x
* @returns
*/
export const isInternalObject = (x: any): boolean => x && (x._internalType instanceof InternalSymbol)
export const isInternalObject = (x: any): boolean =>
x && x._internalType instanceof InternalSymbol

@@ -49,2 +56,2 @@ export const isPlainObject = (obj: any): obj is object => {

return x?._bsontype === 'Binary'
}
}
import { EJSON } from 'bson'
import { isObject } from './type'
export const sleep = (ms: number = 0) => new Promise(r => setTimeout(r, ms))
export const sleep = (ms = 0) => new Promise((r) => setTimeout(r, ms))
const counters: Record<string, number> = {}
export const autoCount = (domain: string = 'any'): number => {
export const autoCount = (domain = 'any'): number => {
if (!counters[domain]) {

@@ -15,5 +15,4 @@ counters[domain] = 0

// 递归过滤对象中的undefiend字段
export const filterUndefined = o => {
export const filterUndefined = (o) => {
// 如果不是对象类型,直接返回

@@ -24,3 +23,3 @@ if (!isObject(o)) {

for (let key in o) {
for (const key in o) {
if (o[key] === undefined) {

@@ -36,3 +35,3 @@ delete o[key]

export const stringifyByEJSON = params => {
export const stringifyByEJSON = (params) => {
// params中删除undefined的key

@@ -44,4 +43,4 @@ params = filterUndefined(params)

export const parseByEJSON = params => {
export const parseByEJSON = (params) => {
return EJSON.parse(params)
}
}

@@ -7,3 +7,3 @@ import {

OrderDirectionList,
FieldType
FieldType,
} from './constant'

@@ -21,9 +21,9 @@ import { Util } from './util'

/**
*
* @static
* @param {StageName:{}|string} stage
* @returns {Boolean}
* @memberof Validate
*/
static isValidAggregation(stage: object): Boolean {
*
* @static
* @param {StageName:{}|string} stage
* @returns {Boolean}
* @memberof Validate
*/
static isValidAggregation(stage: object): boolean {
if (Object.keys(stage).length !== 1) {

@@ -63,3 +63,3 @@ throw new Error('aggregation stage must have one key')

*/
static isInteger(param: string, num: number): Boolean {
static isInteger(param: string, num: number): boolean {
if (!Number.isInteger(num)) {

@@ -71,4 +71,3 @@ throw new Error(param + ErrorCode.IntegerError)

static isProjection(param: string, value: object): Boolean {
static isProjection(param: string, value: object): boolean {
// 遍历value 的 属性值, 只有1,0,ProjectionOperator 三种类型

@@ -83,3 +82,5 @@ if (getType(value) !== 'object') {

if (subValue !== 0 && subValue !== 1) {
throw new Error('if the value in projection is of number, it must be 0 or 1')
throw new Error(
'if the value in projection is of number, it must be 0 or 1'
)
}

@@ -95,3 +96,3 @@ } else if (getType(subValue) === 'object') {

static isOrder(param: string, value: Record<string, any>): Boolean {
static isOrder(param: string, value: Record<string, any>): boolean {
if (getType(value) !== 'object') {

@@ -101,3 +102,3 @@ throw new Error(`${param} order must be an object`)

for (let key in value) {
for (const key in value) {
const subValue = value[key]

@@ -116,3 +117,3 @@ if (subValue !== 1 && subValue !== -1) {

*/
static isFieldOrder(direction: OrderByDirection): Boolean {
static isFieldOrder(direction: OrderByDirection): boolean {
if (OrderDirectionList.indexOf(direction) === -1) {

@@ -131,3 +132,3 @@ throw new Error(ErrorCode.DirectionError)

*/
static isFieldPath(path: string): Boolean {
static isFieldPath(path: string): boolean {
if (!/^[a-zA-Z0-9-_\.]/.test(path)) {

@@ -144,3 +145,3 @@ throw new Error()

*/
static isOperator(op: WhereFilterOp): Boolean {
static isOperator(op: WhereFilterOp): boolean {
if (WhereFilterOpList.indexOf(op) === -1) {

@@ -161,3 +162,3 @@ throw new Error(ErrorCode.OpStrError)

*/
static isCollName(name: string): Boolean {
static isCollName(name: string): boolean {
if (!/^[a-zA-Z0-9]([a-zA-Z0-9-_]){1,32}$/.test(name)) {

@@ -164,0 +165,0 @@ throw new Error(ErrorCode.CollNameError)

@@ -8,7 +8,6 @@ const { Db } = require('../../dist/commonjs/index')

remove: 'database.deleteDocument',
aggregate: 'database.aggregateDocuments'
aggregate: 'database.aggregateDocuments',
}
class MockRequest {
action = null

@@ -18,5 +17,5 @@ params = null

/**
*
* @param {string} action
* @param {any} params
*
* @param {string} action
* @param {any} params
* @returns

@@ -28,7 +27,7 @@ */

this.params = params
if (action === Actions.add) {
data = { _id: '0', insertedCount: 0 }
}
if (action === Actions.get || action === Actions.aggregate) {

@@ -53,7 +52,7 @@ data = { list: [] }

}
return {
code: 0,
requestId: 'test_req_id',
data
data,
}

@@ -63,3 +62,2 @@ }

// mock db

@@ -75,3 +73,3 @@ function getDb() {

Actions,
getDb
}
getDb,
}

@@ -1,3 +0,2 @@

const { Actions, getDb } = require('../_utils')
const { Actions, getDb } = require('../_utils')
const assert = require('assert')

@@ -9,8 +8,9 @@ const { ObjectId } = require('bson')

const { db, req } = getDb()
const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.aggregate([
{
$match: {
name: 'laf'
}
name: 'laf',
},
},

@@ -22,8 +22,8 @@ {

foreignField: '_id',
as: 'user'
}
}
as: 'user',
},
},
])
.end()
// console.log(res, req.params)

@@ -40,9 +40,10 @@ assert.strictEqual(req.action, Actions.aggregate)

const { db, req } = getDb()
await db.collection('tasks')
await db
.collection('tasks')
.aggregate([])
.end()
.catch(err => {
assert.equal(err.toString(),'Error: Aggregation stage cannot be empty' )
})
.catch((err) => {
assert.equal(err.toString(), 'Error: Aggregation stage cannot be empty')
})
})
})
})

@@ -1,3 +0,2 @@

const { Actions, getDb } = require('../_utils')
const { Actions, getDb } = require('../_utils')
const assert = require('assert')

@@ -9,3 +8,4 @@ const { ObjectId } = require('bson')

const { db, req } = getDb()
const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.aggregate()

@@ -16,6 +16,6 @@ .lookup({

foreignField: '_id',
as: 'user'
as: 'user',
})
.end()
// console.log(res, req.params)

@@ -26,3 +26,2 @@ assert.strictEqual(req.action, Actions.aggregate)

const { stageKey, stageValue } = req.params.stages[0]

@@ -35,6 +34,5 @@ assert.ok(stageKey, '$lookup')

assert.ok(!res.code)
assert.ok(res.data instanceof Array)
})
})
})

@@ -1,3 +0,2 @@

const { Actions, getDb } = require('../_utils')
const { Actions, getDb } = require('../_utils')
const assert = require('assert')

@@ -9,3 +8,4 @@ const { ObjectId, Binary } = require('bson')

const { db, req } = getDb()
const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.aggregate()

@@ -16,6 +16,6 @@ .match({

created_at: new Date(),
avatar: new Binary(Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]))
avatar: new Binary(Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72])),
})
.end()
assert.strictEqual(req.action, Actions.aggregate)

@@ -32,6 +32,5 @@ assert.strictEqual(req.params.collectionName, 'tasks')

assert.ok(!res.code)
assert.ok(res.data instanceof Array)
})
})
})

@@ -1,3 +0,2 @@

const { Actions, getDb } = require('../_utils')
const { Actions, getDb } = require('../_utils')
const assert = require('assert')

@@ -11,3 +10,4 @@ const { ObjectId, Binary } = require('bson')

const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72])
const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.doc('nonsense_id')

@@ -18,5 +18,5 @@ .create({

created_at: new Date(),
pic: new Binary(buf)
pic: new Binary(buf),
})
assert.strictEqual(req.action, Actions.add)

@@ -35,3 +35,2 @@ assert.strictEqual(req.params.collectionName, 'tasks')

assert.ok(!res.code)

@@ -46,9 +45,10 @@ assert.ok(res.insertedCount === 1)

const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72])
await db.collection('tasks')
await db
.collection('tasks')
.doc('nonsense_id')
.create({})
.catch(err => {
.catch((err) => {
assert.equal(err.toString(), 'Error: data cannot be empty object')
})
})
})
})

@@ -1,3 +0,2 @@

const { Actions, getDb } = require('../_utils')
const { Actions, getDb } = require('../_utils')
const assert = require('assert')

@@ -9,10 +8,8 @@ const { ObjectId } = require('bson')

const { db, req } = getDb()
const res = await db.collection('tasks')
.doc('test_id')
.get()
const res = await db.collection('tasks').doc('test_id').get()
assert.strictEqual(req.action, Actions.get)
assert.strictEqual(req.params.collectionName, 'tasks')
assert.equal(req.params.limit, 1)
assert.deepEqual(req.params.query, { _id: 'test_id'})
assert.deepEqual(req.params.query, { _id: 'test_id' })

@@ -27,7 +24,5 @@ assert.ok(!res.code)

const id = new ObjectId()
const res = await db.collection('tasks')
.doc(id)
.get()
assert.deepEqual(req.params.query, { _id: { $oid: id.toHexString() }})
const res = await db.collection('tasks').doc(id).get()
assert.deepEqual(req.params.query, { _id: { $oid: id.toHexString() } })
})

@@ -38,9 +33,10 @@

const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.doc('test_id')
.field(['name', 'age', 'gender'])
.get()
assert.deepEqual(req.params.query, { _id: 'test_id'})
assert.deepEqual(req.params.query, { _id: 'test_id' })
assert.deepEqual(req.params.query, { _id: 'test_id' })
assert.deepEqual(req.params.projection, { age: 1, gender: 1, name: 1 })

@@ -52,11 +48,12 @@ })

const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.doc('test_id')
.field({ name: 0, age: 0, gender: 0 })
.get()
assert.deepEqual(req.params.query, { _id: 'test_id'})
assert.deepEqual(req.params.query, { _id: 'test_id' })
assert.deepEqual(req.params.query, { _id: 'test_id' })
assert.deepEqual(req.params.projection, { age: 0, gender: 0, name: 0 })
})
})
})

@@ -1,3 +0,2 @@

const { Actions, getDb } = require('../_utils')
const { Actions, getDb } = require('../_utils')
const assert = require('assert')

@@ -12,3 +11,4 @@ const { ObjectId, Binary } = require('bson')

const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72])
const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.doc('test_id')

@@ -19,5 +19,5 @@ .update({

created_at: new Date(),
pic: new Binary(buf)
pic: new Binary(buf),
})
assert.strictEqual(req.action, Actions.update)

@@ -30,12 +30,14 @@ assert.strictEqual(req.params.collectionName, 'tasks')

// check data
assert.deepEqual(req.params.data.$set.uid, { $oid: uid.toHexString() })
assert.ok(req.params.data.$set.created_at.$date)
assert.equal(req.params.data.$set.pic.$binary.base64, buf.toString('base64'))
assert.equal(
req.params.data.$set.pic.$binary.base64,
buf.toString('base64')
)
// check result
assert.ok(!res.code)
assert.equal(res.updated,1)
assert.equal(res.updated, 1)
})
})
})

@@ -1,2 +0,2 @@

const { getDb } = require('../_utils')
const { getDb } = require('../_utils')
const assert = require('assert')

@@ -7,6 +7,4 @@

const { db, req } = getDb()
const res = await db.collection('tasks')
.field(['name', 'gender'])
.get()
const res = await db.collection('tasks').field(['name', 'gender']).get()
assert.deepEqual(req.params.projection, { name: 1, gender: 1 })

@@ -17,7 +15,5 @@ })

const { db, req } = getDb()
const res = await db.collection('tasks')
.field({ name: 1, gender: 1 })
.get()
assert.deepEqual(req.params.projection, { name: 1, gender: 1 })
const res = await db.collection('tasks').field({ name: 1, gender: 1 }).get()
assert.deepEqual(req.params.projection, { name: 1, gender: 1 })
})

@@ -27,8 +23,6 @@

const { db, req } = getDb()
const res = await db.collection('tasks')
.field({ name: 0, gender: 0 })
.get()
assert.deepEqual(req.params.projection, { name: 0, gender: 0 })
const res = await db.collection('tasks').field({ name: 0, gender: 0 }).get()
assert.deepEqual(req.params.projection, { name: 0, gender: 0 })
})
})
})

@@ -1,3 +0,2 @@

const { Actions, getDb } = require('../_utils')
const { Actions, getDb } = require('../_utils')
const assert = require('assert')

@@ -8,5 +7,4 @@

const { db, req } = getDb()
const res = await db.collection('tasks')
.get()
const res = await db.collection('tasks').get()
assert.strictEqual(req.action, Actions.get)

@@ -23,5 +21,4 @@ assert.strictEqual(req.params.collectionName, 'tasks')

const { db, req } = getDb()
const res = await db.collection('tasks')
.getOne()
const res = await db.collection('tasks').getOne()
assert.strictEqual(req.action, Actions.get)

@@ -35,2 +32,2 @@ assert.strictEqual(req.params.collectionName, 'tasks')

})
})
})

@@ -1,2 +0,2 @@

const { getDb } = require('../_utils')
const { getDb } = require('../_utils')
const assert = require('assert')

@@ -7,5 +7,4 @@

const { db, req } = getDb()
const res = await db.collection('tasks')
.get()
const res = await db.collection('tasks').get()
assert.equal(req.params.limit, 100)

@@ -16,7 +15,4 @@ })

const { db, req } = getDb()
const res = await db.collection('tasks')
.limit(33)
.skip(77)
.get()
const res = await db.collection('tasks').limit(33).skip(77).get()
assert.strictEqual(req.params.limit, 33)

@@ -28,6 +24,7 @@ assert.strictEqual(req.params.offset, 77)

const { db, req } = getDb()
const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.where({
name: 'laf',
status: 1
status: 1,
})

@@ -37,3 +34,3 @@ .limit(555)

.get()
assert.strictEqual(req.params.limit, 555)

@@ -43,2 +40,2 @@ assert.strictEqual(req.params.offset, 999)

})
})
})

@@ -1,2 +0,2 @@

const { getDb } = require('../_utils')
const { getDb } = require('../_utils')
const assert = require('assert')

@@ -7,11 +7,15 @@

const { db, req } = getDb()
const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.orderBy('age', 'asc')
.orderBy('score', 'desc')
.get()
assert.ok(req.params.order.length === 2)
assert.deepEqual(req.params.order[0], { field: 'age', direction: 'asc' })
assert.deepEqual(req.params.order[1], { field: 'score', direction: 'desc' })
assert.deepEqual(req.params.order[1], {
field: 'score',
direction: 'desc',
})
})
})
})

@@ -1,2 +0,2 @@

const { getDb } = require('../_utils')
const { getDb } = require('../_utils')
const assert = require('assert')

@@ -7,6 +7,4 @@

const { db, req } = getDb()
const res = await db.collection('tasks')
.page()
.get()
const res = await db.collection('tasks').page().get()
// console.log(req.params)

@@ -19,6 +17,7 @@ assert.equal(req.params.limit, 10)

const { db, req } = getDb()
const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.page({ current: 3, size: 20 })
.get()
// console.log(req.params)

@@ -29,2 +28,2 @@ assert.equal(req.params.offset, 40)

})
})
})

@@ -1,15 +0,10 @@

const assert = require('assert')
const { ObjectId } = require('bson')
const { getDb } = require('../_utils')
const { getDb } = require('../_utils')
describe('db-ql(unit): db::where()', () => {
it('where({}) should be ok', async () => {
const { db, req } = getDb()
const res = await db.collection('tasks')
.where({})
.get()
const res = await db.collection('tasks').where({}).get()
assert.deepEqual(req.params.query, {})

@@ -20,9 +15,10 @@ })

const { db, req } = getDb()
const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.where({
name: 'laf',
status: 1
status: 1,
})
.get()
assert.deepEqual(req.params.query, { name: 'laf', status: 1 })

@@ -34,11 +30,14 @@ })

const current = new Date()
const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.where({
name: 'laf',
created_at: current
created_at: current,
})
.get()
assert.strictEqual(req.params.query.name, 'laf')
assert.deepEqual(req.params.query.created_at, { $date: current.toISOString()})
assert.deepEqual(req.params.query.created_at, {
$date: current.toISOString(),
})
})

@@ -48,3 +47,4 @@

const { db, req } = getDb()
const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.where({

@@ -55,28 +55,40 @@ reg: /^abc.*$/,

$regex: '^abc.*$',
$options: ''
$options: '',
},
reg4: db.RegExp({ regexp: '^abc.*$' }),
reg5: new RegExp('^abc.*$', 'i')
reg5: new RegExp('^abc.*$', 'i'),
})
.get()
assert.deepEqual(req.params.query.reg, { '$regularExpression': { pattern: '^abc.*$', 'options': ''} })
assert.deepEqual(req.params.query.reg2, { '$regularExpression': { pattern: '^abc.*$', 'options': 'i'} })
assert.deepEqual(req.params.query.reg3, { '$regex': '^abc.*$', '$options': '' })
assert.deepEqual(req.params.query.reg4, { '$regex': '^abc.*$', '$options': '' })
assert.deepEqual(req.params.query.reg5, { '$regularExpression': { pattern: '^abc.*$', 'options': 'i'} })
assert.deepEqual(req.params.query.reg, {
$regularExpression: { pattern: '^abc.*$', options: '' },
})
assert.deepEqual(req.params.query.reg2, {
$regularExpression: { pattern: '^abc.*$', options: 'i' },
})
assert.deepEqual(req.params.query.reg3, {
$regex: '^abc.*$',
$options: '',
})
assert.deepEqual(req.params.query.reg4, {
$regex: '^abc.*$',
$options: '',
})
assert.deepEqual(req.params.query.reg5, {
$regularExpression: { pattern: '^abc.*$', options: 'i' },
})
})
it('where() with ObjectId should be ok', async () => {
const { db, req } = getDb()
const id = new ObjectId()
const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.where({
_id: id
_id: id,
})
.get()
assert.deepEqual(req.params.query._id, { $oid: id.toHexString() })
})
})
})

@@ -1,5 +0,4 @@

const { Actions, getDb } = require('../_utils')
const { Actions, getDb } = require('../_utils')
const assert = require('assert')
const { ObjectId, Binary } = require('bson')
// const { ObjectId, Binary } = require('bson')

@@ -10,12 +9,10 @@ describe('db-ql(unit): db::remove()', () => {

const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72])
const uid = new ObjectId()
const res = await db.collection('tasks')
.where({ name: 'laf' })
.remove()
// const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72])
// const uid = new ObjectId()
const res = await db.collection('tasks').where({ name: 'laf' }).remove()
assert.strictEqual(req.action, Actions.remove)
assert.strictEqual(req.params.collectionName, 'tasks')
// check options
// check options
// console.log(req.params, res)

@@ -26,3 +23,3 @@ assert.equal(req.params.multi, false)

assert.deepEqual(req.params.query, { name: 'laf' })
// check result

@@ -32,2 +29,2 @@ assert.ok(!res.code)

})
})
})

@@ -1,3 +0,2 @@

const { Actions, getDb } = require('../_utils')
const { Actions, getDb } = require('../_utils')
const assert = require('assert')

@@ -12,3 +11,4 @@ const { ObjectId, Binary } = require('bson')

const uid = new ObjectId()
const res = await db.collection('tasks')
const res = await db
.collection('tasks')
.where({ name: 'laf' })

@@ -18,9 +18,9 @@ .update({

created_at: new Date(),
pic: new Binary(buf)
pic: new Binary(buf),
})
assert.strictEqual(req.action, Actions.update)
assert.strictEqual(req.params.collectionName, 'tasks')
// check options
// check options
assert.equal(req.params.multi, false)

@@ -36,8 +36,11 @@ assert.equal(req.params.merge, true)

assert.ok(req.params.data.$set.created_at.$date)
assert.equal(req.params.data.$set.pic.$binary.base64, buf.toString('base64'))
assert.equal(
req.params.data.$set.pic.$binary.base64,
buf.toString('base64')
)
// check result
assert.ok(!res.code)
assert.equal(res.updated,1)
assert.equal(res.updated, 1)
})
})
})
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc