yjh 6 months ago
commit dfec7b48f3

@ -0,0 +1,31 @@
/*
* Eslint config file
* Documentation: https://eslint.org/docs/user-guide/configuring/
* Install the Eslint extension before using this feature.
*/
module.exports = {
env: {
es6: true,
browser: true,
node: true,
},
ecmaFeatures: {
modules: true,
},
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
},
globals: {
wx: true,
App: true,
Page: true,
getCurrentPages: true,
getApp: true,
Component: true,
requirePlugin: true,
requireMiniProgram: true,
},
// extends: 'eslint:recommended',
rules: {},
}

@ -0,0 +1,33 @@
// app.js
App({
onLaunch() {
// 展示本地存储能力
const logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
}
})
},
globalData: {
fileID : "",
filename : "",
array : [],
total : 0,
currentId : 0,
userInfo: null,
course: "",
teacher: "",
date: "",
weekday: '',
start: "",
end: "",
part: 0,
front: 0,
rcount: 1
}
})

@ -0,0 +1,20 @@
{
"pages": [
"pages/list/list",
"pages/card/card",
"pages/checklist/checklist",
"pages/file/file",
"pages/logs/logs",
"pages/rollcall/rollcall",
"pages/cardM/cardM",
"pages/rankings/rankings"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "Weixin",
"navigationBarTextStyle": "black"
},
"style": "v2",
"sitemapLocation": "sitemap.json"
}

File diff suppressed because one or more lines are too long

@ -0,0 +1,6 @@
{
"permissions": {
"openapi": [
]
}
}

@ -0,0 +1,90 @@
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: 'yz-7g23c92hf3223f1d' }) // 使用当前云环境
//引入node-xlsx文件
var xlsx = require('node-xlsx');
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
console.log("filename : " + event.filename);
let fileID = event.fileID;
let filename = event.filename;
//通过fileID下载云存储里的excel文件
const res = await cloud.downloadFile({
fileID: fileID,
})
console.log('下载的文件', res);
const file_xlsx = res.fileContent
//解析excel文件
var files = xlsx.parse(file_xlsx); //获取到已经解析的对象数组
var arr = files[0].data;
for (let i = 0; i < arr.length; i++) {
arr[i][0] = String(arr[i][0]); // 或者 arr[i][0] = arr[i][0].toString();
}
console.log('获得内容表格数组', arr);
var row = 0;
// console.log(arr[row][0].length + " " + arr[row][0][0]);
function judgeID(s) {
var len = s.length;
if(len == 0) return false;
var flag = true;
for(var i = 0; i < arr[row][0].length; ++i)
if(!(s[i] >= '0' && s[i] <= '9'))
flag = false;
return flag;
}
while (row <= arr.length) {
if(arr[row].length == 0) {
row++;
continue ;
}
if(judgeID(arr[row][0])) break;
row++;
}
// console.log("数据从第" + row + "行开始");
if(row == arr.length) {
return "error";
//返回错误
}
// var namelist = "namelist" + filename;
// console.log("namelist = " + namelist);
while(row <= arr.length - 1 && arr[row].length > 0 && judgeID(arr[row][0])) {
var _student_ID = arr[row][0].toString();
while(_student_ID.length < 9) _student_ID = '0' + _student_ID;
var _name = arr[row][1];
var _attendance_count = arr[row][2]; // 提取被点名次数
if (_attendance_count === undefined || _attendance_count === "") {
_attendance_count = 0; // 如果为空白默认设置为0
}
var _score = arr[row][3]; // 提取积分
if (_score === undefined || _score === "") {
_score = 0; // 如果为空白默认设置为0
}
// console.log(_student_ID + " " + _name);
db.collection("namelist").add({
data: {
student_ID: _student_ID,
name: _name,
attendance_count: _attendance_count,
score: _score,
filename : filename,
state : "present"
}
})
row++;
}
console.log("数据上传完成");
console.log(fileID);
cloud.deleteFile({
fileList: [fileID],
success(res) {
console.log(res, '文件删除成功')
},
fail(res) {
console.log(res, "文件删除失败")
}
})
return "success";
}

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../adler-32/bin/adler32.njs" "$@"
else
exec node "$basedir/../adler-32/bin/adler32.njs" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\adler-32\bin\adler32.njs" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../adler-32/bin/adler32.njs" $args
} else {
& "$basedir/node$exe" "$basedir/../adler-32/bin/adler32.njs" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../adler-32/bin/adler32.njs" $args
} else {
& "node$exe" "$basedir/../adler-32/bin/adler32.njs" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../crc-32/bin/crc32.njs" "$@"
else
exec node "$basedir/../crc-32/bin/crc32.njs" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\crc-32\bin\crc32.njs" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../crc-32/bin/crc32.njs" $args
} else {
& "$basedir/node$exe" "$basedir/../crc-32/bin/crc32.njs" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../crc-32/bin/crc32.njs" $args
} else {
& "node$exe" "$basedir/../crc-32/bin/crc32.njs" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../node-xlsx/lib/bin/cli.js" "$@"
else
exec node "$basedir/../node-xlsx/lib/bin/cli.js" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-xlsx\lib\bin\cli.js" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../node-xlsx/lib/bin/cli.js" $args
} else {
& "$basedir/node$exe" "$basedir/../node-xlsx/lib/bin/cli.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../node-xlsx/lib/bin/cli.js" $args
} else {
& "node$exe" "$basedir/../node-xlsx/lib/bin/cli.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../protobufjs/bin/pbjs" "$@"
else
exec node "$basedir/../protobufjs/bin/pbjs" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\protobufjs\bin\pbjs" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../protobufjs/bin/pbjs" $args
} else {
& "$basedir/node$exe" "$basedir/../protobufjs/bin/pbjs" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../protobufjs/bin/pbjs" $args
} else {
& "node$exe" "$basedir/../protobufjs/bin/pbjs" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../protobufjs/bin/pbts" "$@"
else
exec node "$basedir/../protobufjs/bin/pbts" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\protobufjs\bin\pbts" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../protobufjs/bin/pbts" $args
} else {
& "$basedir/node$exe" "$basedir/../protobufjs/bin/pbts" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../protobufjs/bin/pbts" $args
} else {
& "node$exe" "$basedir/../protobufjs/bin/pbts" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../printj/bin/printj.njs" "$@"
else
exec node "$basedir/../printj/bin/printj.njs" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\printj\bin\printj.njs" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../printj/bin/printj.njs" $args
} else {
& "$basedir/node$exe" "$basedir/../printj/bin/printj.njs" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../printj/bin/printj.njs" $args
} else {
& "node$exe" "$basedir/../printj/bin/printj.njs" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../semver/bin/semver" "$@"
else
exec node "$basedir/../semver/bin/semver" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../semver/bin/semver" $args
} else {
& "$basedir/node$exe" "$basedir/../semver/bin/semver" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../semver/bin/semver" $args
} else {
& "node$exe" "$basedir/../semver/bin/semver" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../sshpk/bin/sshpk-conv" "$@"
else
exec node "$basedir/../sshpk/bin/sshpk-conv" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\sshpk\bin\sshpk-conv" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../sshpk/bin/sshpk-conv" $args
} else {
& "$basedir/node$exe" "$basedir/../sshpk/bin/sshpk-conv" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../sshpk/bin/sshpk-conv" $args
} else {
& "node$exe" "$basedir/../sshpk/bin/sshpk-conv" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../sshpk/bin/sshpk-sign" "$@"
else
exec node "$basedir/../sshpk/bin/sshpk-sign" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\sshpk\bin\sshpk-sign" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../sshpk/bin/sshpk-sign" $args
} else {
& "$basedir/node$exe" "$basedir/../sshpk/bin/sshpk-sign" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../sshpk/bin/sshpk-sign" $args
} else {
& "node$exe" "$basedir/../sshpk/bin/sshpk-sign" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../sshpk/bin/sshpk-verify" "$@"
else
exec node "$basedir/../sshpk/bin/sshpk-verify" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\sshpk\bin\sshpk-verify" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../sshpk/bin/sshpk-verify" $args
} else {
& "$basedir/node$exe" "$basedir/../sshpk/bin/sshpk-verify" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../sshpk/bin/sshpk-verify" $args
} else {
& "node$exe" "$basedir/../sshpk/bin/sshpk-verify" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../ts-node/dist/bin.js" "$@"
else
exec node "$basedir/../ts-node/dist/bin.js" "$@"
fi

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../ts-node/dist/bin-script.js" "$@"
else
exec node "$basedir/../ts-node/dist/bin-script.js" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\ts-node\dist\bin-script.js" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../ts-node/dist/bin-script.js" $args
} else {
& "$basedir/node$exe" "$basedir/../ts-node/dist/bin-script.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../ts-node/dist/bin-script.js" $args
} else {
& "node$exe" "$basedir/../ts-node/dist/bin-script.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../ts-node/dist/bin-transpile.js" "$@"
else
exec node "$basedir/../ts-node/dist/bin-transpile.js" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\ts-node\dist\bin-transpile.js" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../ts-node/dist/bin-transpile.js" $args
} else {
& "$basedir/node$exe" "$basedir/../ts-node/dist/bin-transpile.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../ts-node/dist/bin-transpile.js" $args
} else {
& "node$exe" "$basedir/../ts-node/dist/bin-transpile.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\ts-node\dist\bin.js" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../ts-node/dist/bin.js" $args
} else {
& "$basedir/node$exe" "$basedir/../ts-node/dist/bin.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../ts-node/dist/bin.js" $args
} else {
& "node$exe" "$basedir/../ts-node/dist/bin.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../ts-node/dist/bin-script-deprecated.js" "$@"
else
exec node "$basedir/../ts-node/dist/bin-script-deprecated.js" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\ts-node\dist\bin-script-deprecated.js" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../ts-node/dist/bin-script-deprecated.js" $args
} else {
& "$basedir/node$exe" "$basedir/../ts-node/dist/bin-script-deprecated.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../ts-node/dist/bin-script-deprecated.js" $args
} else {
& "node$exe" "$basedir/../ts-node/dist/bin-script-deprecated.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../typescript/bin/tsc" "$@"
else
exec node "$basedir/../typescript/bin/tsc" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\typescript\bin\tsc" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../typescript/bin/tsc" $args
} else {
& "$basedir/node$exe" "$basedir/../typescript/bin/tsc" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../typescript/bin/tsc" $args
} else {
& "node$exe" "$basedir/../typescript/bin/tsc" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../typescript/bin/tsserver" "$@"
else
exec node "$basedir/../typescript/bin/tsserver" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\typescript\bin\tsserver" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../typescript/bin/tsserver" $args
} else {
& "$basedir/node$exe" "$basedir/../typescript/bin/tsserver" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../typescript/bin/tsserver" $args
} else {
& "node$exe" "$basedir/../typescript/bin/tsserver" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../uuid/bin/uuid" "$@"
else
exec node "$basedir/../uuid/bin/uuid" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\uuid\bin\uuid" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../uuid/bin/uuid" $args
} else {
& "$basedir/node$exe" "$basedir/../uuid/bin/uuid" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../uuid/bin/uuid" $args
} else {
& "node$exe" "$basedir/../uuid/bin/uuid" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,12 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../xlsx/bin/xlsx.njs" "$@"
else
exec node "$basedir/../xlsx/bin/xlsx.njs" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\xlsx\bin\xlsx.njs" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../xlsx/bin/xlsx.njs" $args
} else {
& "$basedir/node$exe" "$basedir/../xlsx/bin/xlsx.njs" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../xlsx/bin/xlsx.njs" $args
} else {
& "node$exe" "$basedir/../xlsx/bin/xlsx.njs" $args
}
$ret=$LASTEXITCODE
}
exit $ret

File diff suppressed because it is too large Load Diff

@ -0,0 +1,9 @@
root = true
[!{node_modules}/**]
end_of_line = lf
charset = utf-8
[{*.js,*.ts}]
indent_style = space
indent_size = 2

@ -0,0 +1,43 @@
{
"extends": [
"prettier"
],
"plugins": [
"typescript"
],
"rules": {
"indent": [
"error",
2,
{
"SwitchCase": 1,
"flatTernaryExpressions": true
}
],
"no-unused-vars": "warn",
"typescript/no-unused-vars": "warn",
"semi": [
"error",
"never"
],
"quotes": [
"error",
"single",
{
"avoidEscape": true
}
]
},
"env": {
"es6": true,
"node": true
},
"parser": "typescript-eslint-parser",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module",
"ecmaFeatures": {
"modules": true
}
}
}

@ -0,0 +1,29 @@
module.exports = {
// 一行最多 100 字符
printWidth: 100,
// 使用 2 个空格缩进
tabWidth: 2,
// 不使用缩进符,而使用空格
useTabs: false,
// 行尾无分号
semi: false,
// 使用单引号
singleQuote: true,
// 对象的 key 仅在必要时用引号
quoteProps: 'as-needed',
// 末尾不需要逗号
trailingComma: 'none',
// 大括号内的首尾需要空格
bracketSpacing: true,
// 每个文件格式化的范围是文件的全部内容
rangeStart: 0,
rangeEnd: Infinity,
// 不需要写文件开头的 @prettier
requirePragma: false,
// 不需要自动在文件开头插入 @prettier
insertPragma: false,
// 使用默认的折行标准
proseWrap: 'preserve',
// 换行符使用 lf
endOfLine: 'lf'
}

@ -0,0 +1,119 @@
# @cloudbase/database
[![NPM Version](https://img.shields.io/npm/v/@cloudbase/database.svg?style=flat)](https://www.npmjs.com/package/@cloudbase/database)
[![](https://img.shields.io/npm/dt/@cloudbase/database.svg)](https://www.npmjs.com/package/@cloudbase/database)
## 介绍
提供 TCB JS SDK 操作数据库的接口。
## 安装
```
yarn add @cloudbase/database
```
## 使用
使用 `@cloudbase/database` 时,需要提供发送请求的类 `reqClass`
```js
// index.js
const database = require('@cloudbase/database/').Db;
const Request = require('./request');
class Tcb {
...
database(dbConfig) {
database.reqClass = Request;
return new database(dbConfig);
}
}
```
实现 `Request` 类,需要提供异步的 `send` 方法。
```js
// request.js
// 进一步处理,鉴权等...
const requestHandler = require('requestHandler')
class Request {
constructor(config) {
this.config = config
}
async send(action, data) {
const params = Object.assign({}, data, {
action
})
const slowQueryWarning = setTimeout(() => {
console.warn(
'Database operation is longer than 3s. Please check query performance and your network environment.'
)
}, 3000)
try {
return await requestHandler({
timeout: this.config.timeout,
config: this.config.config,
params,
method: 'post',
headers: {
'content-type': 'application/json'
}
})
} finally {
clearTimeout(slowQueryWarning)
}
}
}
module.exports = Request
```
请求数据样例
```json
{
"url": "https://tcb-admin.tencentcloudapi.com/admin?eventId=1554896261428_92044",
"method": "post",
"timeout": 15000,
"headers": { "user-agent": "tcb-admin-sdk/1.4.6", "content-type": "application/json" },
"body": {
"collectionName": "coll-1",
"action": "database.addCollection",
"envName": "base-830cab",
"timestamp": 1554896261428,
"eventId": "1554896261428_92044",
"authorization": "q-sign-algorithm=sha1&q-ak=xxx&q-sign-time=1554896260;1554897160&q-key-time=1554896260;1554897160&q-header-list=content-type;user-agent&q-url-param-list=action;collectionname;envname;eventid;timestamp&q-signature=xxxxx",
"sdk_version": "1.4.6"
},
"json": true
}
```
## 开发指南
### 注意
当前 database 库是通过分支来控制了两个不同的版本,主干版提供给@cloudbase/js-sdk 库使用feature/support_db_2.0 分支提供给@cloudbase/node-sdk 库使用。
两个分支区别:
support_db_2.0 分支进行了数据库接口的升级,将原有的 json 协议转换为 mongo 支持的 bson 协议处理,目的是解决旧接口存在的问题,描述如下
- 日期对象 是走约定协议处理,即转换为 {$date: timestamp},这种方式应摒弃(EJSON 协议可解决)
- 无法支持 null, NaN 等特殊类型处理(EJSON 协议可解决)
- serverDate 这种自定义类型的实现,是继续保留 还是摒弃
- 接口实现混杂,普通 CRUD 接口均走 flexdb而聚合事务又用 runcommand 方式
- 原插入文档接口返回 docId 形式混杂
目前仅针对服务端 sdk @cloudbase/node-sdk 完成了升级,而客户端 sdk @cloudbase/js-sdk 以及 小程序端 SDK 仍保留为旧接口形式。
### 开发及发布事项
1. 数据库接口的改动务必补充测试用例验证
2. 发布时,约定 feature/support_db_2.0 分支上发布正式版for @cloudbase/node-sdk使用master 分支上发布 beta 版 (for @cloudbase/js-sdk)使用。两 sdk 均通过锁版本方式依赖该库,不会受自动更新依赖影响。

@ -0,0 +1,11 @@
export declare class ObjectId {
id: string;
constructor({ id }?: {
id?: string;
});
readonly _internalType: import("../utils/symbol").InternalSymbol;
parse(): {
$oid: string;
};
}
export declare function ObjectIdConstructor(opt: any): ObjectId;

@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const symbol_1 = require("../helper/symbol");
class ObjectId {
constructor({ id = '' } = {}) {
this.id = id;
}
get _internalType() {
return symbol_1.SYMBOL_OBJECTID;
}
parse() {
return {
$oid: this.id
};
}
}
exports.ObjectId = ObjectId;
function ObjectIdConstructor(opt) {
return new ObjectId(opt);
}
exports.ObjectIdConstructor = ObjectIdConstructor;

@ -0,0 +1,29 @@
export default class Aggregation {
_db: any;
_request: any;
_stages: any[];
_collectionName: string;
constructor(db?: any, collectionName?: any, rawPipeline?: any);
end(): Promise<any>;
unwrap(): any[];
done(): {
[x: number]: any;
}[];
_pipe(stage: any, param: any, raw?: boolean): this;
addFields(param: any): this;
bucket(param: any): this;
bucketAuto(param: any): this;
count(param: any): this;
geoNear(param: any): this;
group(param: any): this;
limit(param: any): this;
match(param: any): this;
project(param: any): this;
lookup(param: any): this;
replaceRoot(param: any): this;
sample(param: any): this;
skip(param: any): this;
sort(param: any): this;
sortByCount(param: any): this;
unwind(param: any): this;
}

@ -0,0 +1,124 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const index_1 = require("./index");
const bson_1 = require("bson");
const query_1 = require("./serializer/query");
const utils_1 = require("./utils/utils");
const type_1 = require("./utils/type");
const validate_1 = require("./validate");
const point_1 = require("./geo/point");
class Aggregation {
constructor(db, collectionName, rawPipeline) {
this._stages = [];
if (db && collectionName) {
this._db = db;
this._request = new index_1.Db.reqClass(this._db.config);
this._collectionName = collectionName;
if (rawPipeline && rawPipeline.length > 0) {
rawPipeline.forEach((stage) => {
validate_1.Validate.isValidAggregation(stage);
const stageName = Object.keys(stage)[0];
this._pipe(stageName, stage[stageName], true);
});
}
}
}
async end() {
if (!this._collectionName || !this._db) {
throw new Error('Aggregation pipeline cannot send request');
}
const result = await this._request.send('database.aggregateDocuments', {
collectionName: this._collectionName,
stages: this._stages
});
if (result && result.data && result.data.list) {
return {
requestId: result.requestId,
data: result.data.list.map(bson_1.EJSON.parse)
};
}
return result;
}
unwrap() {
return this._stages;
}
done() {
return this._stages.map(({ stageKey, stageValue }) => {
return {
[stageKey]: JSON.parse(stageValue)
};
});
}
_pipe(stage, param, raw = false) {
let transformParam = '';
if (type_1.getType(param) === 'object') {
transformParam = utils_1.stringifyByEJSON(param);
}
else {
transformParam = JSON.stringify(param);
}
this._stages.push({
stageKey: raw ? stage : `$${stage}`,
stageValue: transformParam
});
return this;
}
addFields(param) {
return this._pipe('addFields', param);
}
bucket(param) {
return this._pipe('bucket', param);
}
bucketAuto(param) {
return this._pipe('bucketAuto', param);
}
count(param) {
return this._pipe('count', param);
}
geoNear(param) {
if (param.query) {
param.query = query_1.QuerySerializer.encode(param.query);
}
if (param.distanceMultiplier && typeof (param.distanceMultiplier) === 'number') {
param.distanceMultiplier = param.distanceMultiplier;
}
if (param.near) {
param.near = new point_1.Point(param.near.longitude, param.near.latitude).toJSON();
}
return this._pipe('geoNear', param);
}
group(param) {
return this._pipe('group', param);
}
limit(param) {
return this._pipe('limit', param);
}
match(param) {
return this._pipe('match', query_1.QuerySerializer.encode(param));
}
project(param) {
return this._pipe('project', param);
}
lookup(param) {
return this._pipe('lookup', param);
}
replaceRoot(param) {
return this._pipe('replaceRoot', param);
}
sample(param) {
return this._pipe('sample', param);
}
skip(param) {
return this._pipe('skip', param);
}
sort(param) {
return this._pipe('sort', param);
}
sortByCount(param) {
return this._pipe('sortByCount', param);
}
unwind(param) {
return this._pipe('unwind', param);
}
}
exports.default = Aggregation;

@ -0,0 +1,17 @@
import { DocumentReference } from './document';
import { Query, QueryOption, UpdateOption } from './query';
import Aggregation from './aggregate';
export declare class CollectionReference extends Query {
protected _transactionId: string;
readonly name: string;
doc(docID: string | number): DocumentReference;
add(data: any): Promise<{
ids?: string[];
id?: string;
inserted?: number;
ok?: number;
requestId: string;
}>;
aggregate(rawPipeline?: object[]): Aggregation;
options(apiOptions: QueryOption | UpdateOption): CollectionReference;
}

@ -0,0 +1,72 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const document_1 = require("./document");
const query_1 = require("./query");
const aggregate_1 = require("./aggregate");
const datatype_1 = require("./serializer/datatype");
const utils_1 = require("./utils/utils");
const validate_1 = require("./validate");
const type_1 = require("./utils/type");
class CollectionReference extends query_1.Query {
constructor(db, coll, apiOptions, transactionId) {
super(db, coll, '', apiOptions, transactionId);
if (transactionId) {
this._transactionId = transactionId;
}
}
get name() {
return this._coll;
}
doc(docID) {
if (typeof docID !== 'string' && typeof docID !== 'number') {
throw new Error('docId必须为字符串或数字');
}
return new document_1.DocumentReference(this._db, this._coll, this._apiOptions, docID, this._transactionId);
}
async add(data) {
let transformData = data;
if (!type_1.isArray(data)) {
transformData = [data];
}
transformData = transformData.map(item => {
return utils_1.stringifyByEJSON(datatype_1.serialize(item));
});
let params = {
collectionName: this._coll,
data: transformData
};
if (this._transactionId) {
params.transactionId = this._transactionId;
}
const res = await this._request.send('database.insertDocument', params, utils_1.getReqOpts(this._apiOptions));
if (res.code) {
return res;
}
if (!type_1.isArray(data)) {
if (this._transactionId) {
return {
inserted: 1,
ok: 1,
id: res.data.insertedIds[0],
requestId: res.requestId
};
}
return {
id: res.data.insertedIds[0],
requestId: res.requestId
};
}
return {
ids: res.data.insertedIds,
requestId: res.requestId
};
}
aggregate(rawPipeline = []) {
return new aggregate_1.default(this._db, this._coll, (this._apiOptions.raw || false) ? rawPipeline : []);
}
options(apiOptions) {
validate_1.Validate.isValidOptions(apiOptions);
return new CollectionReference(this._db, this._coll, apiOptions, this._transactionId);
}
}
exports.CollectionReference = CollectionReference;

@ -0,0 +1,175 @@
import { QueryCommand } from './commands/query';
import { LogicCommand } from './commands/logic';
import { UpdateCommand } from './commands/update';
import Aggregation from './aggregate';
export declare type IQueryCondition = Record<string, any> | LogicCommand;
export declare const Command: {
eq(val: any): QueryCommand;
neq(val: any): QueryCommand;
lt(val: any): QueryCommand;
lte(val: any): QueryCommand;
gt(val: any): QueryCommand;
gte(val: any): QueryCommand;
in(val: any): QueryCommand;
nin(val: any): QueryCommand;
all(val: any): QueryCommand;
elemMatch(val: any): QueryCommand;
exists(val: boolean): QueryCommand;
size(val: number): QueryCommand;
mod(): QueryCommand;
geoNear(val: any): QueryCommand;
geoWithin(val: any): QueryCommand;
geoIntersects(val: any): QueryCommand;
and(...__expressions__: import("./serializer/datatype").IQueryCondition[]): LogicCommand;
nor(...__expressions__: import("./serializer/datatype").IQueryCondition[]): LogicCommand;
or(...__expressions__: import("./serializer/datatype").IQueryCondition[]): LogicCommand;
not(...__expressions__: import("./serializer/datatype").IQueryCondition[]): LogicCommand;
set(val: any): UpdateCommand;
remove(): UpdateCommand;
inc(val: number): UpdateCommand;
mul(val: number): UpdateCommand;
push(...args: any[]): UpdateCommand;
pull(values: any): UpdateCommand;
pullAll(values: any): UpdateCommand;
pop(): UpdateCommand;
shift(): UpdateCommand;
unshift(...__values__: any[]): UpdateCommand;
addToSet(values: any): UpdateCommand;
rename(values: any): UpdateCommand;
bit(values: any): UpdateCommand;
max(values: any): UpdateCommand;
min(values: any): UpdateCommand;
expr(values: AggregationOperator): {
$expr: AggregationOperator;
};
jsonSchema(schema: any): {
$jsonSchema: any;
};
text(values: string | {
search: string;
language?: string;
caseSensitive?: boolean;
diacriticSensitive: boolean;
}): {
$search: {
(regexp: string | RegExp): number;
(searcher: {
[Symbol.search](string: string): number;
}): number;
};
$language?: undefined;
$caseSensitive?: undefined;
$diacriticSensitive?: undefined;
} | {
$search: string;
$language: string;
$caseSensitive: boolean;
$diacriticSensitive: boolean;
};
aggregate: {
pipeline(): Aggregation;
abs: (param: any) => AggregationOperator;
add: (param: any) => AggregationOperator;
ceil: (param: any) => AggregationOperator;
divide: (param: any) => AggregationOperator;
exp: (param: any) => AggregationOperator;
floor: (param: any) => AggregationOperator;
ln: (param: any) => AggregationOperator;
log: (param: any) => AggregationOperator;
log10: (param: any) => AggregationOperator;
mod: (param: any) => AggregationOperator;
multiply: (param: any) => AggregationOperator;
pow: (param: any) => AggregationOperator;
sqrt: (param: any) => AggregationOperator;
subtract: (param: any) => AggregationOperator;
trunc: (param: any) => AggregationOperator;
arrayElemAt: (param: any) => AggregationOperator;
arrayToObject: (param: any) => AggregationOperator;
concatArrays: (param: any) => AggregationOperator;
filter: (param: any) => AggregationOperator;
in: (param: any) => AggregationOperator;
indexOfArray: (param: any) => AggregationOperator;
isArray: (param: any) => AggregationOperator;
map: (param: any) => AggregationOperator;
range: (param: any) => AggregationOperator;
reduce: (param: any) => AggregationOperator;
reverseArray: (param: any) => AggregationOperator;
size: (param: any) => AggregationOperator;
slice: (param: any) => AggregationOperator;
zip: (param: any) => AggregationOperator;
and: (param: any) => AggregationOperator;
not: (param: any) => AggregationOperator;
or: (param: any) => AggregationOperator;
cmp: (param: any) => AggregationOperator;
eq: (param: any) => AggregationOperator;
gt: (param: any) => AggregationOperator;
gte: (param: any) => AggregationOperator;
lt: (param: any) => AggregationOperator;
lte: (param: any) => AggregationOperator;
neq: (param: any) => AggregationOperator;
cond: (param: any) => AggregationOperator;
ifNull: (param: any) => AggregationOperator;
switch: (param: any) => AggregationOperator;
dateFromParts: (param: any) => AggregationOperator;
dateFromString: (param: any) => AggregationOperator;
dayOfMonth: (param: any) => AggregationOperator;
dayOfWeek: (param: any) => AggregationOperator;
dayOfYear: (param: any) => AggregationOperator;
isoDayOfWeek: (param: any) => AggregationOperator;
isoWeek: (param: any) => AggregationOperator;
isoWeekYear: (param: any) => AggregationOperator;
millisecond: (param: any) => AggregationOperator;
minute: (param: any) => AggregationOperator;
month: (param: any) => AggregationOperator;
second: (param: any) => AggregationOperator;
hour: (param: any) => AggregationOperator;
week: (param: any) => AggregationOperator;
year: (param: any) => AggregationOperator;
literal: (param: any) => AggregationOperator;
mergeObjects: (param: any) => AggregationOperator;
objectToArray: (param: any) => AggregationOperator;
allElementsTrue: (param: any) => AggregationOperator;
anyElementTrue: (param: any) => AggregationOperator;
setDifference: (param: any) => AggregationOperator;
setEquals: (param: any) => AggregationOperator;
setIntersection: (param: any) => AggregationOperator;
setIsSubset: (param: any) => AggregationOperator;
setUnion: (param: any) => AggregationOperator;
concat: (param: any) => AggregationOperator;
dateToString: (param: any) => AggregationOperator;
indexOfBytes: (param: any) => AggregationOperator;
indexOfCP: (param: any) => AggregationOperator;
split: (param: any) => AggregationOperator;
strLenBytes: (param: any) => AggregationOperator;
strLenCP: (param: any) => AggregationOperator;
strcasecmp: (param: any) => AggregationOperator;
substr: (param: any) => AggregationOperator;
substrBytes: (param: any) => AggregationOperator;
substrCP: (param: any) => AggregationOperator;
toLower: (param: any) => AggregationOperator;
toUpper: (param: any) => AggregationOperator;
meta: (param: any) => AggregationOperator;
addToSet: (param: any) => AggregationOperator;
avg: (param: any) => AggregationOperator;
first: (param: any) => AggregationOperator;
last: (param: any) => AggregationOperator;
max: (param: any) => AggregationOperator;
min: (param: any) => AggregationOperator;
push: (param: any) => AggregationOperator;
stdDevPop: (param: any) => AggregationOperator;
stdDevSamp: (param: any) => AggregationOperator;
sum: (param: any) => AggregationOperator;
let: (param: any) => AggregationOperator;
};
project: {
slice: (param: any) => ProjectionOperator;
elemMatch: (param: any) => ProjectionOperator;
};
};
export declare class AggregationOperator {
constructor(name: any, param: any);
}
export declare class ProjectionOperator {
constructor(name: any, param: any);
}
export default Command;

@ -0,0 +1,285 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const query_1 = require("./commands/query");
const logic_1 = require("./commands/logic");
const update_1 = require("./commands/update");
const type_1 = require("./utils/type");
const aggregate_1 = require("./aggregate");
exports.Command = {
eq(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.EQ, [val]);
},
neq(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.NEQ, [val]);
},
lt(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.LT, [val]);
},
lte(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.LTE, [val]);
},
gt(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.GT, [val]);
},
gte(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.GTE, [val]);
},
in(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.IN, val);
},
nin(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.NIN, val);
},
all(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.ALL, val);
},
elemMatch(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.ELEM_MATCH, [val]);
},
exists(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.EXISTS, [val]);
},
size(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.SIZE, [val]);
},
mod() {
if (arguments.length == 1)
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.MOD, [arguments[0]]);
if (arguments.length == 2)
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.MOD, [[arguments[0], arguments[1]]]);
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.MOD, arguments);
},
geoNear(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.GEO_NEAR, [val]);
},
geoWithin(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.GEO_WITHIN, [val]);
},
geoIntersects(val) {
return new query_1.QueryCommand(query_1.QUERY_COMMANDS_LITERAL.GEO_INTERSECTS, [val]);
},
and(...__expressions__) {
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);
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);
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);
return new logic_1.LogicCommand(logic_1.LOGIC_COMMANDS_LITERAL.NOT, expressions);
},
set(val) {
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.SET, [val]);
},
remove() {
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.REMOVE, []);
},
inc(val) {
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.INC, [val]);
},
mul(val) {
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.MUL, [val]);
},
push(...args) {
let values;
if (type_1.isObject(args[0]) && args[0].hasOwnProperty('each')) {
values = {};
const options = args[0];
if (options.each !== undefined) {
values['$each'] = options.each;
}
if (options.position !== undefined) {
values['$position'] = options.position;
}
if (options.sort !== undefined) {
values['$sort'] = options.sort;
}
if (options.slice !== undefined) {
values['$slice'] = options.slice;
}
}
else if (type_1.isArray(args[0])) {
values = args[0];
}
else {
values = Array.from(args);
}
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.PUSH, values);
},
pull(values) {
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.PULL, values);
},
pullAll(values) {
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.PULL_ALL, values);
},
pop() {
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.POP, []);
},
shift() {
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.SHIFT, []);
},
unshift(...__values__) {
const values = type_1.isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.UNSHIFT, values);
},
addToSet(values) {
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.ADD_TO_SET, values);
},
rename(values) {
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.RENAME, [values]);
},
bit(values) {
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.BIT, [values]);
},
max(values) {
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.MAX, [values]);
},
min(values) {
return new update_1.UpdateCommand(update_1.UPDATE_COMMANDS_LITERAL.MIN, [values]);
},
expr(values) {
return {
$expr: values
};
},
jsonSchema(schema) {
return {
$jsonSchema: schema
};
},
text(values) {
if (type_1.isString(values)) {
return {
$search: values.search
};
}
else {
return {
$search: values.search,
$language: values.language,
$caseSensitive: values.caseSensitive,
$diacriticSensitive: values.diacriticSensitive
};
}
},
aggregate: {
pipeline() {
return new aggregate_1.default();
},
abs: param => new AggregationOperator('abs', param),
add: param => new AggregationOperator('add', param),
ceil: param => new AggregationOperator('ceil', param),
divide: param => new AggregationOperator('divide', param),
exp: param => new AggregationOperator('exp', param),
floor: param => new AggregationOperator('floor', param),
ln: param => new AggregationOperator('ln', param),
log: param => new AggregationOperator('log', param),
log10: param => new AggregationOperator('log10', param),
mod: param => new AggregationOperator('mod', param),
multiply: param => new AggregationOperator('multiply', param),
pow: param => new AggregationOperator('pow', param),
sqrt: param => new AggregationOperator('sqrt', param),
subtract: param => new AggregationOperator('subtract', param),
trunc: param => new AggregationOperator('trunc', param),
arrayElemAt: param => new AggregationOperator('arrayElemAt', param),
arrayToObject: param => new AggregationOperator('arrayToObject', param),
concatArrays: param => new AggregationOperator('concatArrays', param),
filter: param => new AggregationOperator('filter', param),
in: param => new AggregationOperator('in', param),
indexOfArray: param => new AggregationOperator('indexOfArray', param),
isArray: param => new AggregationOperator('isArray', param),
map: param => new AggregationOperator('map', param),
range: param => new AggregationOperator('range', param),
reduce: param => new AggregationOperator('reduce', param),
reverseArray: param => new AggregationOperator('reverseArray', param),
size: param => new AggregationOperator('size', param),
slice: param => new AggregationOperator('slice', param),
zip: param => new AggregationOperator('zip', param),
and: param => new AggregationOperator('and', param),
not: param => new AggregationOperator('not', param),
or: param => new AggregationOperator('or', param),
cmp: param => new AggregationOperator('cmp', param),
eq: param => new AggregationOperator('eq', param),
gt: param => new AggregationOperator('gt', param),
gte: param => new AggregationOperator('gte', param),
lt: param => new AggregationOperator('lt', param),
lte: param => new AggregationOperator('lte', param),
neq: param => new AggregationOperator('ne', param),
cond: param => new AggregationOperator('cond', param),
ifNull: param => new AggregationOperator('ifNull', param),
switch: param => new AggregationOperator('switch', param),
dateFromParts: param => new AggregationOperator('dateFromParts', param),
dateFromString: param => new AggregationOperator('dateFromString', param),
dayOfMonth: param => new AggregationOperator('dayOfMonth', param),
dayOfWeek: param => new AggregationOperator('dayOfWeek', param),
dayOfYear: param => new AggregationOperator('dayOfYear', param),
isoDayOfWeek: param => new AggregationOperator('isoDayOfWeek', param),
isoWeek: param => new AggregationOperator('isoWeek', param),
isoWeekYear: param => new AggregationOperator('isoWeekYear', param),
millisecond: param => new AggregationOperator('millisecond', param),
minute: param => new AggregationOperator('minute', param),
month: param => new AggregationOperator('month', param),
second: param => new AggregationOperator('second', param),
hour: param => new AggregationOperator('hour', param),
week: param => new AggregationOperator('week', param),
year: param => new AggregationOperator('year', param),
literal: param => new AggregationOperator('literal', param),
mergeObjects: param => new AggregationOperator('mergeObjects', param),
objectToArray: param => new AggregationOperator('objectToArray', 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),
setIsSubset: param => new AggregationOperator('setIsSubset', param),
setUnion: param => new AggregationOperator('setUnion', param),
concat: param => new AggregationOperator('concat', param),
dateToString: param => new AggregationOperator('dateToString', param),
indexOfBytes: param => new AggregationOperator('indexOfBytes', param),
indexOfCP: param => new AggregationOperator('indexOfCP', param),
split: param => new AggregationOperator('split', param),
strLenBytes: param => new AggregationOperator('strLenBytes', param),
strLenCP: param => new AggregationOperator('strLenCP', param),
strcasecmp: param => new AggregationOperator('strcasecmp', param),
substr: param => new AggregationOperator('substr', param),
substrBytes: param => new AggregationOperator('substrBytes', param),
substrCP: param => new AggregationOperator('substrCP', param),
toLower: param => new AggregationOperator('toLower', param),
toUpper: param => new AggregationOperator('toUpper', param),
meta: param => new AggregationOperator('meta', param),
addToSet: param => new AggregationOperator('addToSet', param),
avg: param => new AggregationOperator('avg', param),
first: param => new AggregationOperator('first', param),
last: param => new AggregationOperator('last', param),
max: param => new AggregationOperator('max', param),
min: param => new AggregationOperator('min', param),
push: param => new AggregationOperator('push', param),
stdDevPop: param => new AggregationOperator('stdDevPop', param),
stdDevSamp: param => new AggregationOperator('stdDevSamp', param),
sum: param => new AggregationOperator('sum', param),
let: param => new AggregationOperator('let', param)
},
project: {
slice: param => new ProjectionOperator('slice', param),
elemMatch: param => new ProjectionOperator('elemMatch', param)
}
};
class AggregationOperator {
constructor(name, param) {
this['$' + name] = param;
}
}
exports.AggregationOperator = AggregationOperator;
class ProjectionOperator {
constructor(name, param) {
this['$' + name] = param;
}
}
exports.ProjectionOperator = ProjectionOperator;
exports.default = exports.Command;

@ -0,0 +1,24 @@
import { InternalSymbol } from '../helper/symbol';
export declare const AND = "and";
export declare const OR = "or";
export declare const NOT = "not";
export declare const NOR = "nor";
export declare enum LOGIC_COMMANDS_LITERAL {
AND = "and",
OR = "or",
NOT = "not",
NOR = "nor"
}
export declare class LogicCommand {
fieldName: string | InternalSymbol;
operator: LOGIC_COMMANDS_LITERAL | string;
operands: any[];
_internalType: InternalSymbol;
constructor(operator: LOGIC_COMMANDS_LITERAL | string, operands: any, fieldName?: string | InternalSymbol);
_setFieldName(fieldName: string): LogicCommand;
and(...__expressions__: LogicCommand[]): LogicCommand;
or(...__expressions__: LogicCommand[]): LogicCommand;
}
export declare function isLogicCommand(object: any): object is LogicCommand;
export declare function isKnownLogicCommand(object: any): object is LogicCommand;
export default LogicCommand;

@ -0,0 +1,79 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const symbol_1 = require("../helper/symbol");
const query_1 = require("./query");
exports.AND = 'and';
exports.OR = 'or';
exports.NOT = 'not';
exports.NOR = 'nor';
var LOGIC_COMMANDS_LITERAL;
(function (LOGIC_COMMANDS_LITERAL) {
LOGIC_COMMANDS_LITERAL["AND"] = "and";
LOGIC_COMMANDS_LITERAL["OR"] = "or";
LOGIC_COMMANDS_LITERAL["NOT"] = "not";
LOGIC_COMMANDS_LITERAL["NOR"] = "nor";
})(LOGIC_COMMANDS_LITERAL = exports.LOGIC_COMMANDS_LITERAL || (exports.LOGIC_COMMANDS_LITERAL = {}));
class LogicCommand {
constructor(operator, operands, fieldName) {
this._internalType = symbol_1.SYMBOL_LOGIC_COMMAND;
Object.defineProperties(this, {
_internalType: {
enumerable: false,
configurable: false,
},
});
this.operator = operator;
this.operands = operands;
this.fieldName = fieldName || symbol_1.SYMBOL_UNSET_FIELD_NAME;
if (this.fieldName !== symbol_1.SYMBOL_UNSET_FIELD_NAME) {
if (Array.isArray(operands)) {
operands = operands.slice();
this.operands = operands;
for (let i = 0, len = operands.length; i < len; i++) {
const query = operands[i];
if (isLogicCommand(query) || query_1.isQueryCommand(query)) {
operands[i] = query._setFieldName(this.fieldName);
}
}
}
else {
const query = operands;
if (isLogicCommand(query) || query_1.isQueryCommand(query)) {
operands = query._setFieldName(this.fieldName);
}
}
}
}
_setFieldName(fieldName) {
const operands = this.operands.map(operand => {
if (operand instanceof LogicCommand) {
return operand._setFieldName(fieldName);
}
else {
return operand;
}
});
const command = new LogicCommand(this.operator, operands, fieldName);
return command;
}
and(...__expressions__) {
const expressions = Array.isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
expressions.unshift(this);
return new LogicCommand(LOGIC_COMMANDS_LITERAL.AND, expressions, this.fieldName);
}
or(...__expressions__) {
const expressions = Array.isArray(arguments[0]) ? arguments[0] : Array.from(arguments);
expressions.unshift(this);
return new LogicCommand(LOGIC_COMMANDS_LITERAL.OR, expressions, this.fieldName);
}
}
exports.LogicCommand = LogicCommand;
function isLogicCommand(object) {
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);
}
exports.isKnownLogicCommand = isKnownLogicCommand;
exports.default = LogicCommand;

@ -0,0 +1,73 @@
import { LogicCommand } from './logic';
import { InternalSymbol } from '../helper/symbol';
import { Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon } from '../geo/index';
import { CenterSphere } from '../typings';
export declare const EQ = "eq";
export declare const NEQ = "neq";
export declare const GT = "gt";
export declare const GTE = "gte";
export declare const LT = "lt";
export declare const LTE = "lte";
export declare const IN = "in";
export declare const NIN = "nin";
export declare const ALL = "all";
export declare const ELEM_MATCH = "elemMatch";
export declare const EXISTS = "exists";
export declare const SIZE = "size";
export declare const MOD = "mod";
export declare enum QUERY_COMMANDS_LITERAL {
EQ = "eq",
NEQ = "neq",
GT = "gt",
GTE = "gte",
LT = "lt",
LTE = "lte",
IN = "in",
NIN = "nin",
ALL = "all",
ELEM_MATCH = "elemMatch",
EXISTS = "exists",
SIZE = "size",
MOD = "mod",
GEO_NEAR = "geoNear",
GEO_WITHIN = "geoWithin",
GEO_INTERSECTS = "geoIntersects"
}
export declare class QueryCommand extends LogicCommand {
operator: QUERY_COMMANDS_LITERAL;
constructor(operator: QUERY_COMMANDS_LITERAL, operands: any, fieldName?: string | InternalSymbol);
toJSON(): {
['$ne']: any;
} | {
[x: string]: any;
$ne?: undefined;
};
_setFieldName(fieldName: string): QueryCommand;
eq(val: any): LogicCommand;
neq(val: any): LogicCommand;
gt(val: any): LogicCommand;
gte(val: any): LogicCommand;
lt(val: any): LogicCommand;
lte(val: any): LogicCommand;
in(list: any[]): LogicCommand;
nin(list: any[]): LogicCommand;
geoNear(val: IGeoNearOptions): LogicCommand;
geoWithin(val: IGeoWithinOptions): LogicCommand;
geoIntersects(val: IGeoIntersectsOptions): LogicCommand;
}
export declare function isQueryCommand(object: any): object is QueryCommand;
export declare function isKnownQueryCommand(object: any): object is QueryCommand;
export declare function isComparisonCommand(object: any): object is QueryCommand;
export default QueryCommand;
export interface IGeoNearOptions {
geometry: Point;
maxDistance?: number;
minDistance?: number;
}
export interface IGeoWithinOptions {
geometry?: Polygon | MultiPolygon;
centerSphere?: CenterSphere;
}
export interface IGeoIntersectsOptions {
geometry: Point | LineString | Polygon | MultiPoint | MultiLineString | MultiPolygon;
}

@ -0,0 +1,147 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const logic_1 = require("./logic");
const symbol_1 = require("../helper/symbol");
const index_1 = require("../geo/index");
const type_1 = require("../utils/type");
const validate_1 = require("../validate");
exports.EQ = 'eq';
exports.NEQ = 'neq';
exports.GT = 'gt';
exports.GTE = 'gte';
exports.LT = 'lt';
exports.LTE = 'lte';
exports.IN = 'in';
exports.NIN = 'nin';
exports.ALL = 'all';
exports.ELEM_MATCH = 'elemMatch';
exports.EXISTS = 'exists';
exports.SIZE = 'size';
exports.MOD = 'mod';
var QUERY_COMMANDS_LITERAL;
(function (QUERY_COMMANDS_LITERAL) {
QUERY_COMMANDS_LITERAL["EQ"] = "eq";
QUERY_COMMANDS_LITERAL["NEQ"] = "neq";
QUERY_COMMANDS_LITERAL["GT"] = "gt";
QUERY_COMMANDS_LITERAL["GTE"] = "gte";
QUERY_COMMANDS_LITERAL["LT"] = "lt";
QUERY_COMMANDS_LITERAL["LTE"] = "lte";
QUERY_COMMANDS_LITERAL["IN"] = "in";
QUERY_COMMANDS_LITERAL["NIN"] = "nin";
QUERY_COMMANDS_LITERAL["ALL"] = "all";
QUERY_COMMANDS_LITERAL["ELEM_MATCH"] = "elemMatch";
QUERY_COMMANDS_LITERAL["EXISTS"] = "exists";
QUERY_COMMANDS_LITERAL["SIZE"] = "size";
QUERY_COMMANDS_LITERAL["MOD"] = "mod";
QUERY_COMMANDS_LITERAL["GEO_NEAR"] = "geoNear";
QUERY_COMMANDS_LITERAL["GEO_WITHIN"] = "geoWithin";
QUERY_COMMANDS_LITERAL["GEO_INTERSECTS"] = "geoIntersects";
})(QUERY_COMMANDS_LITERAL = exports.QUERY_COMMANDS_LITERAL || (exports.QUERY_COMMANDS_LITERAL = {}));
class QueryCommand extends logic_1.LogicCommand {
constructor(operator, operands, fieldName) {
super(operator, operands, fieldName);
this.operator = operator;
this._internalType = symbol_1.SYMBOL_QUERY_COMMAND;
}
toJSON() {
switch (this.operator) {
case QUERY_COMMANDS_LITERAL.IN:
case QUERY_COMMANDS_LITERAL.NIN:
return {
['$' + this.operator]: this.operands
};
case QUERY_COMMANDS_LITERAL.NEQ:
return {
['$ne']: this.operands[0]
};
default:
return {
['$' + this.operator]: this.operands[0]
};
}
}
_setFieldName(fieldName) {
const command = new QueryCommand(this.operator, this.operands, fieldName);
return command;
}
eq(val) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.EQ, [val], this.fieldName);
return this.and(command);
}
neq(val) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.NEQ, [val], this.fieldName);
return this.and(command);
}
gt(val) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.GT, [val], this.fieldName);
return this.and(command);
}
gte(val) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.GTE, [val], this.fieldName);
return this.and(command);
}
lt(val) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.LT, [val], this.fieldName);
return this.and(command);
}
lte(val) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.LTE, [val], this.fieldName);
return this.and(command);
}
in(list) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.IN, list, this.fieldName);
return this.and(command);
}
nin(list) {
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.NIN, list, this.fieldName);
return this.and(command);
}
geoNear(val) {
if (!(val.geometry instanceof index_1.Point)) {
throw new TypeError(`"geometry" must be of type Point. Received type ${typeof val.geometry}`);
}
if (val.maxDistance !== undefined && !type_1.isNumber(val.maxDistance)) {
throw new TypeError(`"maxDistance" must be of type Number. Received type ${typeof val.maxDistance}`);
}
if (val.minDistance !== undefined && !type_1.isNumber(val.minDistance)) {
throw new TypeError(`"minDistance" must be of type Number. Received type ${typeof val.minDistance}`);
}
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.GEO_NEAR, [val], this.fieldName);
return this.and(command);
}
geoWithin(val) {
if (!(val.geometry instanceof index_1.MultiPolygon) &&
!(val.geometry instanceof index_1.Polygon) &&
!validate_1.Validate.isCentersPhere(val.centerSphere)) {
throw new TypeError(`"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);
return this.and(command);
}
geoIntersects(val) {
if (!(val.geometry instanceof index_1.Point) &&
!(val.geometry instanceof index_1.LineString) &&
!(val.geometry instanceof index_1.Polygon) &&
!(val.geometry instanceof index_1.MultiPoint) &&
!(val.geometry instanceof index_1.MultiLineString) &&
!(val.geometry instanceof index_1.MultiPolygon)) {
throw new TypeError(`"geometry" must be of type Point, LineString, Polygon, MultiPoint, MultiLineString or MultiPolygon. Received type ${typeof val.geometry}`);
}
const command = new QueryCommand(QUERY_COMMANDS_LITERAL.GEO_INTERSECTS, [val], this.fieldName);
return this.and(command);
}
}
exports.QueryCommand = QueryCommand;
function isQueryCommand(object) {
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;
}
exports.isKnownQueryCommand = isKnownQueryCommand;
function isComparisonCommand(object) {
return isQueryCommand(object);
}
exports.isComparisonCommand = isComparisonCommand;
exports.default = QueryCommand;

@ -0,0 +1,29 @@
import { InternalSymbol } from '../helper/symbol';
export declare enum UPDATE_COMMANDS_LITERAL {
SET = "set",
REMOVE = "remove",
INC = "inc",
MUL = "mul",
PUSH = "push",
PULL = "pull",
PULL_ALL = "pullAll",
POP = "pop",
SHIFT = "shift",
UNSHIFT = "unshift",
ADD_TO_SET = "addToSet",
BIT = "bit",
RENAME = "rename",
MAX = "max",
MIN = "min"
}
export declare class UpdateCommand {
fieldName: string | InternalSymbol;
operator: UPDATE_COMMANDS_LITERAL;
operands: any;
_internalType: InternalSymbol;
constructor(operator: UPDATE_COMMANDS_LITERAL, operands?: any, fieldName?: string | InternalSymbol);
_setFieldName(fieldName: string): UpdateCommand;
}
export declare function isUpdateCommand(object: any): object is UpdateCommand;
export declare function isKnownUpdateCommand(object: any): object is UpdateCommand;
export default UpdateCommand;

@ -0,0 +1,49 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const symbol_1 = require("../helper/symbol");
var UPDATE_COMMANDS_LITERAL;
(function (UPDATE_COMMANDS_LITERAL) {
UPDATE_COMMANDS_LITERAL["SET"] = "set";
UPDATE_COMMANDS_LITERAL["REMOVE"] = "remove";
UPDATE_COMMANDS_LITERAL["INC"] = "inc";
UPDATE_COMMANDS_LITERAL["MUL"] = "mul";
UPDATE_COMMANDS_LITERAL["PUSH"] = "push";
UPDATE_COMMANDS_LITERAL["PULL"] = "pull";
UPDATE_COMMANDS_LITERAL["PULL_ALL"] = "pullAll";
UPDATE_COMMANDS_LITERAL["POP"] = "pop";
UPDATE_COMMANDS_LITERAL["SHIFT"] = "shift";
UPDATE_COMMANDS_LITERAL["UNSHIFT"] = "unshift";
UPDATE_COMMANDS_LITERAL["ADD_TO_SET"] = "addToSet";
UPDATE_COMMANDS_LITERAL["BIT"] = "bit";
UPDATE_COMMANDS_LITERAL["RENAME"] = "rename";
UPDATE_COMMANDS_LITERAL["MAX"] = "max";
UPDATE_COMMANDS_LITERAL["MIN"] = "min";
})(UPDATE_COMMANDS_LITERAL = exports.UPDATE_COMMANDS_LITERAL || (exports.UPDATE_COMMANDS_LITERAL = {}));
class UpdateCommand {
constructor(operator, operands, fieldName) {
this._internalType = symbol_1.SYMBOL_UPDATE_COMMAND;
Object.defineProperties(this, {
_internalType: {
enumerable: false,
configurable: false,
},
});
this.operator = operator;
this.operands = operands;
this.fieldName = fieldName || symbol_1.SYMBOL_UNSET_FIELD_NAME;
}
_setFieldName(fieldName) {
const command = new UpdateCommand(this.operator, this.operands, fieldName);
return command;
}
}
exports.UpdateCommand = UpdateCommand;
function isUpdateCommand(object) {
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);
}
exports.isKnownUpdateCommand = isKnownUpdateCommand;
exports.default = UpdateCommand;

@ -0,0 +1,6 @@
declare const _default: {
db_doc_size_limit: number;
db_realtime_ping_interval: number;
db_realtime_pong_wait_timeout: number;
};
export default _default;

@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = {
db_doc_size_limit: 512 * 1024,
db_realtime_ping_interval: 15 * 1000,
db_realtime_pong_wait_timeout: 15 * 1000,
};

@ -0,0 +1,3 @@
export declare const ERR_CODE: {
[key: string]: string | number;
};

@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ERR_CODE = {
UNKNOWN_ERROR: 'UNKNOWN_ERROR',
SDK_DATABASE_REALTIME_LISTENER_INIT_WATCH_FAIL: 'SDK_DATABASE_REALTIME_LISTENER_INIT_WATCH_FAIL',
SDK_DATABASE_REALTIME_LISTENER_RECONNECT_WATCH_FAIL: 'SDK_DATABASE_REALTIME_LISTENER_RECONNECT_WATCH_FAIL',
SDK_DATABASE_REALTIME_LISTENER_REBUILD_WATCH_FAIL: 'SDK_DATABASE_REALTIME_LISTENER_REBUILD_WATCH_FAIL',
SDK_DATABASE_REALTIME_LISTENER_CLOSE_WATCH_FAIL: 'SDK_DATABASE_REALTIME_LISTENER_CLOSE_WATCH_FAIL',
SDK_DATABASE_REALTIME_LISTENER_SERVER_ERROR_MSG: 'SDK_DATABASE_REALTIME_LISTENER_SERVER_ERROR_MSG',
SDK_DATABASE_REALTIME_LISTENER_RECEIVE_INVALID_SERVER_DATA: 'SDK_DATABASE_REALTIME_LISTENER_RECEIVE_INVALID_SERVER_DATA',
SDK_DATABASE_REALTIME_LISTENER_WEBSOCKET_CONNECTION_ERROR: 'SDK_DATABASE_REALTIME_LISTENER_WEBSOCKET_CONNECTION_ERROR',
SDK_DATABASE_REALTIME_LISTENER_WEBSOCKET_CONNECTION_CLOSED: 'SDK_DATABASE_REALTIME_LISTENER_WEBSOCKET_CONNECTION_CLOSED',
SDK_DATABASE_REALTIME_LISTENER_CHECK_LAST_FAIL: 'SDK_DATABASE_REALTIME_LISTENER_CHECK_LAST_FAIL',
SDK_DATABASE_REALTIME_LISTENER_UNEXPECTED_FATAL_ERROR: 'SDK_DATABASE_REALTIME_LISTENER_UNEXPECTED_FATAL_ERROR'
};

@ -0,0 +1,34 @@
export declare const ERRORS: {
CREATE_WATCH_NET_ERROR: {
code: string;
message: string;
};
CREATE_WACTH_EXCEED_ERROR: {
code: string;
message: string;
};
CREATE_WATCH_SERVER_ERROR: {
code: string;
message: string;
};
CONN_ERROR: {
code: string;
message: string;
};
INVALID_PARAM: {
code: string;
message: string;
};
INSERT_DOC_FAIL: {
code: string;
message: string;
};
DATABASE_TRANSACTION_CONFLICT: {
code: string;
message: string;
};
DATABASE_REQUEST_FAILED: {
code: string;
message: string;
};
};

@ -0,0 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ERRORS = {
CREATE_WATCH_NET_ERROR: {
code: 'CREATE_WATCH_NET_ERROR',
message: 'create watch network error'
},
CREATE_WACTH_EXCEED_ERROR: {
code: 'CREATE_WACTH_EXCEED_ERROR',
message: 'maximum connections exceed'
},
CREATE_WATCH_SERVER_ERROR: {
code: 'CREATE_WATCH_SERVER_ERROR',
message: 'create watch server error'
},
CONN_ERROR: {
code: 'CONN_ERROR',
message: 'connection error'
},
INVALID_PARAM: {
code: 'INVALID_PARAM',
message: 'Invalid request param'
},
INSERT_DOC_FAIL: {
code: 'INSERT_DOC_FAIL',
message: 'insert document failed'
},
DATABASE_TRANSACTION_CONFLICT: {
code: 'DATABASE_TRANSACTION_CONFLICT',
message: 'database transaction conflict'
},
DATABASE_REQUEST_FAILED: {
code: 'DATABASE_REQUEST_FAILED',
message: 'database request failed'
}
};

@ -0,0 +1,54 @@
declare enum ErrorCode {
DocIDError = "\u6587\u6863ID\u4E0D\u5408\u6CD5",
CollNameError = "\u96C6\u5408\u540D\u79F0\u4E0D\u5408\u6CD5",
OpStrError = "\u64CD\u4F5C\u7B26\u4E0D\u5408\u6CD5",
DirectionError = "\u6392\u5E8F\u5B57\u7B26\u4E0D\u5408\u6CD5",
IntergerError = "must be integer",
BooleanError = "must be boolean",
ArrayError = "must be array",
QueryParamTypeError = "\u67E5\u8BE2\u53C2\u6570\u5FC5\u987B\u4E3A\u5BF9\u8C61",
QueryParamValueError = "\u67E5\u8BE2\u53C2\u6570\u5BF9\u8C61\u503C\u4E0D\u80FD\u5747\u4E3Aundefined",
CentersPhereError = "centersPhere\u7ED3\u6784\u4E0D\u5408\u6CD5"
}
declare const FieldType: {
String: string;
Number: string;
Object: string;
Array: string;
Boolean: string;
Null: string;
GeoPoint: string;
GeoLineString: string;
GeoPolygon: string;
GeoMultiPoint: string;
GeoMultiLineString: string;
GeoMultiPolygon: string;
Date: string;
Command: string;
ServerDate: string;
BsonDate: string;
};
declare type OrderByDirection = 'desc' | 'asc';
declare const OrderDirectionList: string[];
declare type WhereFilterOp = '<' | '<=' | '==' | '>=' | '>';
declare const WhereFilterOpList: string[];
declare enum Opeartor {
lt = "<",
gt = ">",
lte = "<=",
gte = ">=",
eq = "=="
}
declare const OperatorMap: {
[Opeartor.eq]: string;
[Opeartor.lt]: string;
[Opeartor.lte]: string;
[Opeartor.gt]: string;
[Opeartor.gte]: string;
};
declare const UpdateOperatorList: string[];
declare enum QueryType {
WHERE = "WHERE",
DOC = "DOC"
}
export { ErrorCode, FieldType, WhereFilterOp, WhereFilterOpList, Opeartor, OperatorMap, OrderByDirection, OrderDirectionList, UpdateOperatorList, QueryType };

@ -0,0 +1,76 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ErrorCode;
(function (ErrorCode) {
ErrorCode["DocIDError"] = "\u6587\u6863ID\u4E0D\u5408\u6CD5";
ErrorCode["CollNameError"] = "\u96C6\u5408\u540D\u79F0\u4E0D\u5408\u6CD5";
ErrorCode["OpStrError"] = "\u64CD\u4F5C\u7B26\u4E0D\u5408\u6CD5";
ErrorCode["DirectionError"] = "\u6392\u5E8F\u5B57\u7B26\u4E0D\u5408\u6CD5";
ErrorCode["IntergerError"] = "must be integer";
ErrorCode["BooleanError"] = "must be boolean";
ErrorCode["ArrayError"] = "must be array";
ErrorCode["QueryParamTypeError"] = "\u67E5\u8BE2\u53C2\u6570\u5FC5\u987B\u4E3A\u5BF9\u8C61";
ErrorCode["QueryParamValueError"] = "\u67E5\u8BE2\u53C2\u6570\u5BF9\u8C61\u503C\u4E0D\u80FD\u5747\u4E3Aundefined";
ErrorCode["CentersPhereError"] = "centersPhere\u7ED3\u6784\u4E0D\u5408\u6CD5";
})(ErrorCode || (ErrorCode = {}));
exports.ErrorCode = ErrorCode;
const FieldType = {
String: 'String',
Number: 'Number',
Object: 'Object',
Array: 'Array',
Boolean: 'Boolean',
Null: 'Null',
GeoPoint: 'GeoPoint',
GeoLineString: 'GeoLineString',
GeoPolygon: 'GeoPolygon',
GeoMultiPoint: 'GeoMultiPoint',
GeoMultiLineString: 'GeoMultiLineString',
GeoMultiPolygon: 'GeoMultiPolygon',
Date: 'Date',
Command: 'Command',
ServerDate: 'ServerDate',
BsonDate: 'BsonDate'
};
exports.FieldType = FieldType;
const OrderDirectionList = ['desc', 'asc'];
exports.OrderDirectionList = OrderDirectionList;
const WhereFilterOpList = ['<', '<=', '==', '>=', '>'];
exports.WhereFilterOpList = WhereFilterOpList;
var Opeartor;
(function (Opeartor) {
Opeartor["lt"] = "<";
Opeartor["gt"] = ">";
Opeartor["lte"] = "<=";
Opeartor["gte"] = ">=";
Opeartor["eq"] = "==";
})(Opeartor || (Opeartor = {}));
exports.Opeartor = Opeartor;
const OperatorMap = {
[Opeartor.eq]: '$eq',
[Opeartor.lt]: '$lt',
[Opeartor.lte]: '$lte',
[Opeartor.gt]: '$gt',
[Opeartor.gte]: '$gte'
};
exports.OperatorMap = OperatorMap;
const UpdateOperatorList = [
'$set',
'$inc',
'$mul',
'$unset',
'$push',
'$pop',
'$unshift',
'$shift',
'$currentDate',
'$each',
'$position'
];
exports.UpdateOperatorList = UpdateOperatorList;
var QueryType;
(function (QueryType) {
QueryType["WHERE"] = "WHERE";
QueryType["DOC"] = "DOC";
})(QueryType || (QueryType = {}));
exports.QueryType = QueryType;

@ -0,0 +1,14 @@
import { IWatchOptions, DBRealtimeListener } from './typings/index';
export declare class DocumentReference {
readonly id: string | number;
readonly _transactionId: string;
readonly projection: Object;
private _apiOptions;
set(data: Object): Promise<any>;
update(data: Object): Promise<any>;
delete(): Promise<any>;
remove(): Promise<any>;
get(): Promise<any>;
field(projection: Object): DocumentReference;
watch: (options: IWatchOptions) => DBRealtimeListener;
}

@ -0,0 +1,219 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const index_1 = require("./index");
const util_1 = require("./util");
const update_1 = require("./serializer/update");
const datatype_1 = require("./serializer/datatype");
const update_2 = require("./commands/update");
const websocket_client_1 = require("./realtime/websocket-client");
const constant_1 = require("./constant");
const utils_1 = require("./utils/utils");
const code_1 = require("./const/code");
const bson_1 = require("bson");
class DocumentReference {
constructor(db, coll, apiOptions, docID, transactionId) {
this.watch = (options) => {
if (!index_1.Db.ws) {
index_1.Db.ws = new websocket_client_1.RealtimeWebSocketClient({
context: {
appConfig: {
docSizeLimit: 1000,
realtimePingInterval: 10000,
realtimePongWaitTimeout: 5000,
request: this.request
}
}
});
}
return index_1.Db.ws.watch(Object.assign(Object.assign({}, options), { envId: this._db.config.env, collectionName: this._coll, query: JSON.stringify({
_id: this.id
}) }));
};
this._db = db;
this._coll = coll;
this.id = docID;
this._transactionId = transactionId;
this.request = new index_1.Db.reqClass(this._db.config);
this._apiOptions = apiOptions;
}
async create(data) {
if (this.id) {
data['_id'] = this.id;
}
let params = {
collectionName: this._coll,
data: [utils_1.stringifyByEJSON(datatype_1.serialize(data))],
transactionId: this._transactionId
};
const res = await this.request.send('database.insertDocument', params, utils_1.getReqOpts(this._apiOptions));
if (res.code) {
return res;
}
if (this._transactionId) {
return {
inserted: 1,
ok: 1,
id: res.data.insertedIds[0],
requestId: res.requestId
};
}
return {
id: res.data.insertedIds[0],
requestId: res.requestId
};
}
async set(data) {
if (!this.id) {
return utils_1.processReturn(this._db.config.throwOnCode, Object.assign(Object.assign({}, code_1.ERRORS.INVALID_PARAM), { message: 'docId不能为空' }));
}
if (!data || typeof data !== 'object') {
return utils_1.processReturn(this._db.config.throwOnCode, Object.assign(Object.assign({}, code_1.ERRORS.INVALID_PARAM), { message: '参数必需是非空对象' }));
}
if (data.hasOwnProperty('_id')) {
return utils_1.processReturn(this._db.config.throwOnCode, Object.assign(Object.assign({}, code_1.ERRORS.INVALID_PARAM), { message: '不能更新_id的值' }));
}
let hasOperator = false;
const checkMixed = objs => {
if (typeof objs === 'object') {
for (let key in objs) {
if (objs[key] instanceof update_2.UpdateCommand) {
hasOperator = true;
}
else if (typeof objs[key] === 'object') {
checkMixed(objs[key]);
}
}
}
};
checkMixed(data);
if (hasOperator) {
return utils_1.processReturn(this._db.config.throwOnCode, Object.assign(Object.assign({}, code_1.ERRORS.DATABASE_REQUEST_FAILED), { message: 'update operator complicit' }));
}
let param = {
collectionName: this._coll,
queryType: constant_1.QueryType.DOC,
data: utils_1.stringifyByEJSON(datatype_1.serialize(data)),
transactionId: this._transactionId,
multi: false,
merge: false,
upsert: true
};
if (this.id) {
param['query'] = utils_1.stringifyByEJSON({ _id: this.id });
}
const res = await this.request.send('database.modifyDocument', param, utils_1.getReqOpts(this._apiOptions));
if (res.code) {
return res;
}
if (this._transactionId) {
return {
updated: res.data.updated,
upserted: [{ _id: res.data.upsert_id }],
requestId: res.requestId
};
}
return {
updated: res.data.updated,
upsertedId: res.data.upsert_id,
requestId: res.requestId
};
}
async update(data) {
if (!data || typeof data !== 'object') {
return utils_1.processReturn(this._db.config.throwOnCode, Object.assign(Object.assign({}, code_1.ERRORS.INVALID_PARAM), { message: '参数必需是非空对象' }));
}
if (data.hasOwnProperty('_id')) {
return utils_1.processReturn(this._db.config.throwOnCode, Object.assign(Object.assign({}, code_1.ERRORS.INVALID_PARAM), { message: '不能更新_id的值' }));
}
const query = utils_1.stringifyByEJSON({ _id: this.id });
const param = {
collectionName: this._coll,
transactionId: this._transactionId,
data: update_1.UpdateSerializer.encodeEJSON(data, this._apiOptions.raw || false),
query,
queryType: constant_1.QueryType.DOC,
multi: false,
merge: true,
upsert: false
};
const res = await this.request.send('database.modifyDocument', param, utils_1.getReqOpts(this._apiOptions));
if (res.code) {
return res;
}
return {
updated: res.data.updated,
requestId: res.requestId
};
}
async delete() {
return this.remove();
}
async remove() {
const query = utils_1.stringifyByEJSON({ _id: this.id });
const param = {
collectionName: this._coll,
transactionId: this._transactionId,
query: query,
queryType: constant_1.QueryType.DOC,
multi: false
};
const res = await this.request.send('database.removeDocument', param, utils_1.getReqOpts(this._apiOptions));
if (res.code) {
return res;
}
return {
deleted: res.data.deleted,
requestId: res.requestId
};
}
async get() {
const query = utils_1.stringifyByEJSON({ _id: this.id });
const { projection } = this._apiOptions;
const param = {
collectionName: this._coll,
query,
transactionId: this._transactionId,
queryType: constant_1.QueryType.DOC,
multi: false
};
if (projection) {
param.projection = utils_1.stringifyByEJSON(projection);
}
const res = await this.request.send('database.getDocument', param, utils_1.getReqOpts(this._apiOptions));
if (res.code) {
return res;
}
const list = res.data.list.map(item => bson_1.EJSON.parse(item));
const documents = util_1.Util.formatResDocumentData(list);
if (this._transactionId) {
return {
data: documents[0] || null,
requestId: res.requestId
};
}
return {
data: documents,
requestId: res.requestId,
offset: res.data.offset,
limit: res.data.limit
};
}
field(projection) {
let transformProjection = {};
for (let k in projection) {
if (typeof projection[k] === 'boolean') {
transformProjection[k] = projection[k] === true ? 1 : 0;
}
if (typeof projection[k] === 'number') {
transformProjection[k] = projection[k] > 0 ? 1 : 0;
}
if (typeof projection[k] === 'object') {
transformProjection[k] = projection[k];
}
}
let newApiOption = Object.assign({}, this._apiOptions);
newApiOption.projection = transformProjection;
return new DocumentReference(this._db, this._coll, newApiOption, this.id, this._transactionId);
}
}
exports.DocumentReference = DocumentReference;

@ -0,0 +1,6 @@
export * from './point';
export * from './lineString';
export * from './polygon';
export * from './multiPoint';
export * from './multiLineString';
export * from './multiPolygon';

@ -0,0 +1,11 @@
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./point"));
__export(require("./lineString"));
__export(require("./polygon"));
__export(require("./multiPoint"));
__export(require("./multiLineString"));
__export(require("./multiPolygon"));

@ -0,0 +1,24 @@
export interface ISerializedPoint {
type: string;
coordinates: [number, number];
}
export interface ISerializedLineString {
type: string;
coordinates: [number, number][];
}
export interface ISerializedPolygon {
type: string;
coordinates: [number, number][][];
}
export interface ISerializedMultiPoint {
type: string;
coordinates: [number, number][];
}
export interface ISerializedMultiLineString {
type: string;
coordinates: [number, number][][];
}
export interface ISerializedMultiPolygon {
type: string;
coordinates: [number, number][][][];
}

@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

@ -0,0 +1,19 @@
import { Point } from './point';
import { ISerializedLineString } from './interface';
export declare class LineString {
readonly points: Point[];
constructor(points: Point[]);
parse(key: any): {
[x: number]: {
type: string;
coordinates: number[][];
};
};
toJSON(): {
type: string;
coordinates: number[][];
};
static validate(lineString: ISerializedLineString): boolean;
static isClosed(lineString: LineString): boolean;
readonly _internalType: import("../utils/symbol").InternalSymbol;
}

@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const symbol_1 = require("../helper/symbol");
const point_1 = require("./point");
const type_1 = require("../utils/type");
class LineString {
constructor(points) {
if (!type_1.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_1.Point)) {
throw new TypeError(`"points" must be of type Point[]. Received type ${typeof point}[]`);
}
});
this.points = points;
}
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)
};
}
static validate(lineString) {
if (lineString.type !== 'LineString' || !type_1.isArray(lineString.coordinates)) {
return false;
}
for (let point of lineString.coordinates) {
if (!type_1.isNumber(point[0]) || !type_1.isNumber(point[1])) {
return false;
}
}
return true;
}
static isClosed(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;
}
}
get _internalType() {
return symbol_1.SYMBOL_GEO_LINE_STRING;
}
}
exports.LineString = LineString;

@ -0,0 +1,18 @@
import { LineString } from './lineString';
import { ISerializedMultiLineString } from './interface';
export declare class MultiLineString {
readonly lines: LineString[];
constructor(lines: LineString[]);
parse(key: any): {
[x: number]: {
type: string;
coordinates: number[][][];
};
};
toJSON(): {
type: string;
coordinates: number[][][];
};
static validate(multiLineString: ISerializedMultiLineString): boolean;
readonly _internalType: import("../utils/symbol").InternalSymbol;
}

@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const symbol_1 = require("../helper/symbol");
const type_1 = require("../utils/type");
const lineString_1 = require("./lineString");
class MultiLineString {
constructor(lines) {
if (!type_1.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_1.LineString)) {
throw new TypeError(`"lines" must be of type LineString[]. Received type ${typeof line}[]`);
}
});
this.lines = lines;
}
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]);
})
};
}
static validate(multiLineString) {
if (multiLineString.type !== 'MultiLineString' || !type_1.isArray(multiLineString.coordinates)) {
return false;
}
for (let line of multiLineString.coordinates) {
for (let point of line) {
if (!type_1.isNumber(point[0]) || !type_1.isNumber(point[1])) {
return false;
}
}
}
return true;
}
get _internalType() {
return symbol_1.SYMBOL_GEO_MULTI_LINE_STRING;
}
}
exports.MultiLineString = MultiLineString;

@ -0,0 +1,18 @@
import { Point } from './point';
import { ISerializedMultiPoint } from './interface';
export declare class MultiPoint {
readonly points: Point[];
constructor(points: Point[]);
parse(key: any): {
[x: number]: {
type: string;
coordinates: number[][];
};
};
toJSON(): {
type: string;
coordinates: number[][];
};
static validate(multiPoint: ISerializedMultiPoint): boolean;
readonly _internalType: import("../utils/symbol").InternalSymbol;
}

@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const symbol_1 = require("../helper/symbol");
const point_1 = require("./point");
const type_1 = require("../utils/type");
class MultiPoint {
constructor(points) {
if (!type_1.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_1.Point)) {
throw new TypeError(`"points" must be of type Point[]. Received type ${typeof point}[]`);
}
});
this.points = points;
}
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)
};
}
static validate(multiPoint) {
if (multiPoint.type !== 'MultiPoint' || !type_1.isArray(multiPoint.coordinates)) {
return false;
}
for (let point of multiPoint.coordinates) {
if (!type_1.isNumber(point[0]) || !type_1.isNumber(point[1])) {
return false;
}
}
return true;
}
get _internalType() {
return symbol_1.SYMBOL_GEO_MULTI_POINT;
}
}
exports.MultiPoint = MultiPoint;

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save