Skip to content

Commit

Permalink
Prettier format
Browse files Browse the repository at this point in the history
  • Loading branch information
adaex committed May 31, 2021
1 parent f767823 commit c53f085
Show file tree
Hide file tree
Showing 9 changed files with 76 additions and 86 deletions.
22 changes: 13 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
[![npm downloads](https://img.shields.io/npm/dm/coa-ali-sls.svg?style=flat-square)](http://npm-stat.com/charts.html?package=coa-ali-sls)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://github.com/coajs/coa-ali-sls/pulls)

轻量的阿里云日志服务SDK for Node.js
轻量的阿里云日志服务 SDK for Node.js

来源于一个实际生产项目,将用到的API和业务解耦后封装成此库
来源于一个实际生产项目,将用到的 API 和业务解耦后封装成此库

后续会根据实际使用情况优化和扩充新的服务。如果急需用到其他接口,可以直接使用阿里云官方SDK [aliyun-sdk/sls](https://github.com/aliyun-UED/aliyun-sdk-js/tree/master/samples/sls) 或查看阿里云官方 [帮助文档](https://help.aliyun.com/document_detail/141789.html)
后续会根据实际使用情况优化和扩充新的服务。如果急需用到其他接口,可以直接使用阿里云官方 SDK [aliyun-sdk/sls](https://github.com/aliyun-UED/aliyun-sdk-js/tree/master/samples/sls) 或查看阿里云官方 [帮助文档](https://help.aliyun.com/document_detail/141789.html)

## 特征

- 覆盖了绝大多数使用场景
- 相对于官方的SDK,无任何第三方依赖,更轻量简洁
- 相对于官方的 SDK,无任何第三方依赖,更轻量简洁
- 统一了异步表现形式,全部返回 Promise
- 内置类型引用,无需额外查看文档,开箱即用,IDE友好
- 内置类型引用,无需额外查看文档,开箱即用,IDE 友好

## 快速开始

Expand Down Expand Up @@ -44,7 +44,8 @@ const config = {
const service = new AliSlsService(config)

// 定义查询的开始时间和结束时间
const from = dayjs('2020-01-01'), to = dayjs('2020-01-02')
const from = dayjs('2020-01-01')
const to = dayjs('2020-01-02')

// 查询指定 Project 下某个 Logstore 中的日志数据
service.getLogs('project-name', from, to)
Expand All @@ -62,10 +63,13 @@ import { dayjs } from 'coa-helper'
import { AliSlsQuery, AliSlsService } from 'coa-ali-sls'

// 创建service实例
const service = new AliSlsService({ /* ... */})
const service = new AliSlsService({
/* ... */
})

// 定义查询的开始时间和结束时间
const from = dayjs('2020-01-01'), to = dayjs('2020-01-02')
const from = dayjs('2020-01-01'),
to = dayjs('2020-01-02')

// 定义查询条件(全部用法如下)
const query = new AliSlsQuery()
Expand All @@ -86,4 +90,4 @@ const query = new AliSlsQuery()

// 按照查询条件查询指定 Project 下某个 Logstore 中的日志数据
await service.getLogs('project-name', from, to, { query })
```
```
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"scripts": {
"dev": "tsc -w",
"build": "rm -rf dist && tsc && cp package.json *.md dist && rm -rf dist/test",
"lint": "eslint . ",
"lint": "eslint .",
"prettier": "prettier -w .",
"sync": "curl -X PUT 'https://npm.taobao.org/sync/coa-ali-sls?sync_upstream=true'"
},
Expand Down
1 change: 0 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,3 @@ export { AliSlsBin } from './lib/AliSlsBin'
export { AliSlsQuery } from './lib/AliSlsQuery'
export { AliSlsService } from './service/AliSlsService'
export { AliSls } from './typings'

40 changes: 18 additions & 22 deletions src/lib/AliSlsBin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,13 @@ import { secure } from 'coa-secure'
import { AliSls } from '../typings'

export class AliSlsBin {

private readonly config: AliSls.Config

constructor (config: AliSls.Config) {
constructor(config: AliSls.Config) {
this.config = config
}

async get (url: string, params: AliSls.Dic) {

async get(url: string, params: AliSls.Dic) {
const path = url + '?' + this.getSortQueryString(params)

const headers = this.getHeaders('GET', path)
Expand All @@ -23,56 +21,55 @@ export class AliSlsBin {
return this.resultResponse(result)
}

async getBody (url: string, params: AliSls.Dic) {
async getBody(url: string, params: AliSls.Dic) {
const { body } = await this.get(url, params)
return body
}

protected resultError (e: any) {
protected resultError(e: any) {
const data = e.response.data
die.hint(data.errorMessage, 400, data.errorCode)
}

private resultResponse (result: any) {
private resultResponse(result: any) {
const body = result.data as AliSls.Dic[]
const info = {} as AliSls.Dic<string>
const info: AliSls.Dic<string> = {}
_.forEach(result.headers, (v, k) => {
if (k.startsWith('x-log-')) info[_.camelCase(k.substr(6))] = v
})
_.forEach(body, v => {
delete v['__time__']
delete v['__source__']
_.forEach(body, (v) => {
delete v.__time__
delete v.__source__
})
return { body, info }
}

private getSortQueryString (params: AliSls.Dic<string | number | boolean | undefined>) {
private getSortQueryString(params: AliSls.Dic<string | number | boolean | undefined>) {
const list = [] as string[]
_.forEach(params, (v, k) => {
list.push(k + '=' + v)
})
return list.sort().join('&')
}

private getHeaders (method: string, path: string, headers: AliSls.Dic<string> = {}) {

private getHeaders(method: string, path: string, headers: AliSls.Dic<string> = {}) {
_.defaults(headers, {
'x-log-bodyrawsize': '0',
'x-log-apiversion': '0.6.0',
'x-log-signaturemethod': 'hmac-sha1',
})

headers['Date'] = new Date().toUTCString()
headers.Date = new Date().toUTCString()
headers['Content-MD5'] = ''
headers['Content-Type'] = ''
headers['Authorization'] = this.signature(method, path, headers)
headers.Authorization = this.signature(method, path, headers)

return headers
}

private signature (method: string, path: string, headers: AliSls.Dic<string>) {

const x_list = [] as string[], signs = [] as string[]
private signature(method: string, path: string, headers: AliSls.Dic<string>) {
const x_list = [] as string[]
const signs = [] as string[]

_.forEach(headers, (v, k) => {
k.startsWith('x-log') && x_list.push(k + ':' + v)
Expand All @@ -81,13 +78,12 @@ export class AliSlsBin {
signs.push(method || '')
signs.push(headers['Content-Md5'] || '')
signs.push(headers['Content-Type'] || '')
signs.push(headers['Date'] || '')
signs.push(headers.Date || '')
signs.push(...x_list.sort())
signs.push(path)

const signature = secure.sha1_hmac(signs.join('\n'), this.config.accessKeySecret, 'base64')

return `LOG ${this.config.accessKeyId}:${signature}`
}

}
}
66 changes: 28 additions & 38 deletions src/lib/AliSlsQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@ import { _ } from 'coa-helper'

// SLS 极简的SLS SQLBuilder
export class AliSlsQuery {

private _column = [] as string []
private _where = [] as string[]
private _groupBy = [] as string[]
private _orderBy = [] as string[]
private readonly _column = [] as string[]
private readonly _where = [] as string[]
private readonly _groupBy = [] as string[]
private readonly _orderBy = [] as string[]
private _limit = 0 as number

constructor () {
constructor() {
return this
}

Expand All @@ -20,9 +19,8 @@ export class AliSlsQuery {
* @param field 列名
* @param alias 输出别名
*/
column (field: string, alias?: string) {
if (alias)
field += ' as ' + alias
column(field: string, alias?: string) {
if (alias) field += ' as ' + alias
this._column.push(field)
return this
}
Expand All @@ -33,7 +31,7 @@ export class AliSlsQuery {
* @param format 格式化
* @param alias 输出别名
*/
dateFormat (field: string, format: string, alias?: string) {
dateFormat(field: string, format: string, alias?: string) {
return this.column(`date_format(${field},'${format}')`, alias)
}

Expand All @@ -42,7 +40,7 @@ export class AliSlsQuery {
* @param field 列名
* @param alias 输出别名
*/
approxDistinct (field: string, alias?: string) {
approxDistinct(field: string, alias?: string) {
const stmt = `approx_distinct(${field})`
return this.column(stmt, alias)
}
Expand All @@ -55,7 +53,7 @@ export class AliSlsQuery {
* @param field 列名
* @param alias 输出别名
*/
timeSeries (field = '__time__', alias: string, grainSize: string, format = '%Y-%m-%d %H:%i', padding = 0) {
timeSeries(field: string, alias: string, grainSize: string, format = '%Y-%m-%d %H:%i', padding = 0) {
return this.column(`time_series(${field}, '${grainSize}', '${format}', '${padding}')`, alias)
}

Expand All @@ -65,7 +63,7 @@ export class AliSlsQuery {
* @param value 值
* @param checkEmpty true进行空值检查,为空的不查询 false 不进行空值检查
*/
eq (field: string, value: string, checkEmpty = false) {
eq(field: string, value: string, checkEmpty = false) {
return this.where(field, '=', value, true, checkEmpty)
}

Expand All @@ -75,7 +73,7 @@ export class AliSlsQuery {
* @param value 值
* @param checkEmpty true进行空值检查,为空的不查询 false 不进行空值检查
*/
ne (field: string, value: string, checkEmpty = false) {
ne(field: string, value: string, checkEmpty = false) {
return this.where(field, '<>', value, true, checkEmpty)
}

Expand All @@ -84,9 +82,8 @@ export class AliSlsQuery {
* @param field 字段名
* @param values 字符串数组
*/
notIn (field: string, values: string[]) {
if (!values.length)
return this
notIn(field: string, values: string[]) {
if (!values.length) return this

_.forEach(values, (value, i) => {
values[i] = `'${value}'`
Expand All @@ -101,15 +98,15 @@ export class AliSlsQuery {
* @param likes 带%的数据库语句
* @param checkEmpty true进行空值检查,为空的不查询 false 不进行空值检查
*/
notLike (field: string, likes: string, checkEmpty = false) {
notLike(field: string, likes: string, checkEmpty = false) {
return this.where(field, 'not like', likes, true, checkEmpty)
}

/**
* 根据字段分组
* @param fields 字段名
*/
groupBy (...fields: string[]) {
groupBy(...fields: string[]) {
this._groupBy.push(...fields)
return this
}
Expand All @@ -118,7 +115,7 @@ export class AliSlsQuery {
* 根据字段排序
* @param fields 字段名
*/
orderBy (...fields: string[]) {
orderBy(...fields: string[]) {
this._orderBy.push(...fields)
return this
}
Expand All @@ -127,33 +124,28 @@ export class AliSlsQuery {
* 获取前n条记录
* @param count 前n项记录
*/
limit (count: number) {
limit(count: number) {
this._limit = count
return this
}

/**
* 获取sql语句
*/
toQuery () {
toQuery() {
let sql = '* | '

this._column.length || die.hint('缺少column')
sql += 'select ' + this._column.join(', ')

if (this._where.length)
sql += ' where ' + this._where.join(' and ')
if (this._where.length) sql += ' where ' + this._where.join(' and ')

if (this._groupBy.length)
sql += ' group by ' + this._groupBy.join(',')
if (this._groupBy.length) sql += ' group by ' + this._groupBy.join(',')

if (this._orderBy.length)
sql += ' order by ' + this._orderBy.join(',')
if (this._orderBy.length) sql += ' order by ' + this._orderBy.join(',')

if (this._limit > 0)
sql += ' limit ' + this._limit
else
echo.warn('SLS查询的结果行数默认为')
if (this._limit > 0) sql += ' limit ' + this._limit
else echo.warn('SLS查询的结果行数默认为')
return sql
}

Expand All @@ -162,7 +154,7 @@ export class AliSlsQuery {
* @param field 字段名
* @param alias 输出别名
*/
count (field = '*', alias?: string) {
count(field = '*', alias?: string) {
return this.column(`count(${field})`, alias)
}

Expand All @@ -174,13 +166,11 @@ export class AliSlsQuery {
* @param wrapValue 是否把值当作字符串处理 是:在查询值两边添加单引号 否:不添加单引号
* @param checkEmpty true进行空值检查,false不进行空值检查
*/
private where (field: string, operate: string, value: string, wrapValue: boolean, checkEmpty: boolean) {
private where(field: string, operate: string, value: string, wrapValue: boolean, checkEmpty: boolean) {
// 当开启空值检查 并且当前值为空的时候跳过该值
if (checkEmpty && !value)
return this
if (checkEmpty && !value) return this
const str = wrapValue ? `"${field}" ${operate} '${value}'` : `"${field}" ${operate} ${value}`
this._where.push(str)
return this
}

}
}
Loading

0 comments on commit c53f085

Please sign in to comment.